在ASP.NET中使用JSON

news/2024/6/3 5:19:05 标签: asp.net, webservice, json, string, textbox, 服务器

本篇将简单的介绍一个在.NET中实现JSON的API,然后使用该API做个C/S ASP.NET的小练习。

Json.NET的简单介绍

首先介绍一个为方便在.NET中使用JSON的API,Json.NET。它方便我们读取从浏览器流向服务器的JSON对象,也方便在响应流中写入JSON对象。这里下载:Json.NET。

Json.NET只提供了服务器端的方法,主要有实现JSON文本与XML互相转换的类,有自定义读写JSON的JsonReader类和JsonWriter类,还有一个非自定义读写JSON的JavaScriptSerializer类。

ASP.NET AJAX中,服务器端由JavaScriptSerializer类的几个方法来用于实现序列化和反序列化能力。在Json.NET中,服务器端的序列化 和反序列化能力则主要由JavaScriptConvert类的几个方法提供。本篇的例子只使用了JavaScriptConvert。

  1. JavaScriptConvert
    • Json.NET中,这个类用于序列化和反序列化JavaScript对象。
    • 这个类有两个方法:
      1. SerializeObject(object value, params JsonConverter[] converters),序列化,它有个重载方法SerializeObject(object value)
      2. DeserializeObject(string value, Type type),反序列化,它有个重载方法DeserializeObject(string value)

在客户端,Json.NET未提供支持。如果需要则可以结合使用上一篇“What is JSON:初识JSON”提到的json.js来处理客户端的系列化与反序列化。

下面我们尝试用这个API在ASP.NET中实现用JSON交互数据。

使用Json.NET在C/S中交互JSON数据的简单例子

  1. 先新建一个ASP.NET 网站。

  2. 将下载到的Binary文件夹中的Newtonsoft.Json.dll和Newtonsoft.Json.XML放入网站的bin文件,当然要先新建bin文件夹。然后对dll添加引用。

  3. 切 换到设计模式,从标准工具箱向页面上添加三个Label,Text分别为EmployeeID、EmployeeName、EmployeeInfo;三 个Textbox,ID分别为txtID、txtName、txtInfo;然后添加一个Button,ID为btnToJSONString,Text 为Invoke ToJSONString;然后添加一个Textbox,ID为txtJSON,Textmode为MultiLine,rows设为5;接着再分别添加 一个Button和Textbox,ID为btnToObject、txtStrEmployee,Button的Text为Invoke ToStrEmployee。
  4. 添加一个WebService项目。 
    • 编写一个Employee类,然后两个WebMethod,接着在项目中对该Web服务添加引用。代码如下:

      using  System;
      using  System.Web;
      using  System.Collections;
      using  System.Web.Services;
      using  System.Web.Services.Protocols;
      using  Newtonsoft.Json;

      class  Employee
      {
          
      private   string [] employeeInfo;
          
          
      public   int  EmployeeID;
          
      public   string  EmployeeName;
          
      public   string [] EmployeeInfo
          {
              
      get  {  return   this .employeeInfo; }
              
      set  {  this .employeeInfo  =  value;}
          }
      }

      /**/ ///   <summary>
      ///  WebService 的摘要说明
      ///   </summary>
      [WebService(Namespace  =   " http://tempuri.org/ " )]
      [WebServiceBinding(ConformsTo 
      =  WsiProfiles.BasicProfile1_1)]
      public   class  WebService : System.Web.Services.WebService {

          
      public  WebService () {

              
      // 如果使用设计的组件,请取消注释以下行 
              
      // InitializeComponent(); 
          }

          [WebMethod]
          
      public   string  ToJSONString( int  employeeID,  string  employeeName,  string [] employeeInfo) 
          {
              Employee employee 
      =   new  Employee();
              employee.EmployeeID 
      =  employeeID;
              employee.EmployeeName 
      =  employeeName;
              employee.EmployeeInfo 
      =  employeeInfo;

              
      return  JavaScriptConvert.SerializeObject(employee);
          }

          [WebMethod]
          
      public   string  ToStrEmployee( string  strJSON)
          {
              Employee decerializedEmployee 
      =  (Employee)JavaScriptConvert.DeserializeObject(strJSON,  typeof (Employee));
              
      return   " ID:  "   +  decerializedEmployee.EmployeeID  +   " "
                  
      +   " Name:  "   +  decerializedEmployee.EmployeeName  +   " "
                  
      +   " Info:  "   +  decerializedEmployee.EmployeeInfo.ToString();
          }   
      }

                          成员的属性类型分别为数字、字符串和数组。

5、对两个Button编写事件代码

    

 

     protected   void  btnToJSONString_Click( object  sender, EventArgs e)
    {
        MyServ.WebService MyWebServ 
=   new  MyServ.WebService();
        
string  employeeJSON  =  MyWebServ.ToJSONString(Int32.Parse(txtID.Text), txtName.Text, txtInfo.Text.Split( ' , ' ));
        txtJSON.Text 
=  employeeJSON;
    }
    
protected   void  btnToStrEmployee_Click( object  sender, EventArgs e)
    {
        MyServ.WebService MyWevServ 
=   new  MyServ.WebService();
        
string  strEmployee  =  MyWevServ.ToStrEmployee(txtJSON.Text);
        txtStrEmployee.Text 
=  strEmployee;
    }

 

 

6、 按Ctrl + F5运行;在EmployeeID、EmployeeName、EmployeeInfo中输入123、Hunts.C及一些个人信息(用逗号隔开);点 击Invoke ToJSONString,经服务器端序列化后,结果在txtJSON文本框中;然后点击Invoke ToStrEmployee,此时txtJSON文本框中的JSON文本传输给服务器端,服务器端读取该JSON并反序列化成对象,而后在 txtStrEmployee中写入Employee的成员值。 

                 







Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1400818

 

http://www.niftyadmin.cn/n/1413699.html

相关文章

0302感想

面临着现如今就业难的问题&#xff0c;许多学生在选专业的时候都会纠结到的问题基本上就是要选自己喜欢的还是选未来就业方向好的&#xff0c;最好的方法就是选择自己喜欢且就业方向好的。 在未来&#xff0c;信息时代的不断发展&#xff0c;大数据时代的来临&#xff0c;也意味…

如何:对 JSON 数据进行序列化和反序列化

JSON&#xff08;JavaScript 对象符号&#xff09;是一种高效的数据编码格式&#xff0c;可用于在客户端浏览器和支持 AJAX 的 Web 服务之间快速交换少量数据。 本主题演示如何使用 DataContractJsonSerializer 将 .NET 类型对象序列化为 JSON 编码数据&#xff0c;然后将 JS…

区分数据类型

1.分两类 原始值&#xff0c;引用值&#xff0c;null单独处理 2.区分引用值 function typeFn(target){if(targetnull) return null;let template{[object Array]:array,[object Object]:object,[object Number]:number-object,[object Boolean]:boolean-object,[object String…

iOS播放系统声音

1.声音格式是MP3或m4r的需要转成caf格式&#xff08;可先转成aif , aiff&#xff0c;然后修改后缀&#xff09;2.路径在/System/Library/Audio/UISounds 里&#xff0c;需要更改的可以根据以下列表进行替换3详细列表&#xff1a;信息 ReceivedMessage.caf--收到信息&#xff0c…

linux等待队列wait queue

linux内核的等待队列是在内核中运用非常广泛的数据结构&#xff0c;它是以双循环链表为基础的数据结构&#xff0c;与进程的休眠---唤醒机制紧密相连&#xff0c;可以用来同步对系统资源的访问、异步事件通知、跨进程通信等。 假设进程A想要获取某资源&#xff08;读网卡数据&a…

leetcode ----2个有序数组合并,并去重

解题思想&#xff1a;由于2个数组已经是排序的性质&#xff0c;可以使用2个指针分别指向2个数组&#xff0c;两两比较小数放到新的数组里同时指针向后移动一位&#xff0c;如果是相同&#xff0c;那么2个指针都向后移动1位 参数描述&#xff1a; num1、num2位数组 nums1Size、…

常用的Windows命令

常用的Windows命令 explorer-------打开资源管理器logoff---------注销命令shutdown-------关机命令lusrmgr.msc----本机用户和组services.msc---本地服务设置notepad--------打开记事本net start messenger----开始服务 &#xff08;messenger服务名称&#xff09;net stop me…

解决圆角bitmap保存时背景为黑色

1.cropBitmap.copy(Bitmap.Config.ARGB_8888, true);cropBitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);//格式要为png2. private Bitmap getBitmap(Bitmap bitmap){ Bitmap newBitmap Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config…