欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

.NET中JSON数据进行序列化和反序列化操作分析

程序员文章站 2022-05-04 12:53:20
...
可以使用DataContractJsonSerializer类将类型实例序列化为JSON字符串,并将JSON字符串反序列化为类型实例。 DataContractJsonSerializer在System.Runtime.Serialization.Json命名空间下

,.NET Framework 3.5包含在System.ServiceModel.Web.dll中,需要添加对其的引用;.NET Framework 4在System.Runtime.Serialization中。

  利用DataContractJsonSerializer序列化和反序列化的代码:

 

 1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Web;
  5: using System.Runtime.Serialization.Json;
  6: using System.IO;
  7: using System.Text;
  8:
  9: /// <summary>
  10: /// JSON序列化和反序列化辅助类
  11: /// </summary>
  12: public class JsonHelper
  13: {
  14:     /// <summary>
  15:     /// JSON序列化
  16:     /// </summary>
  17:     public static string JsonSerializer<T>(T t)
  18:     {
  19:         DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
  20:         MemoryStream ms = new MemoryStream();
  21:         ser.WriteObject(ms, t);
  22:         string jsonString = Encoding.UTF8.GetString(ms.ToArray());
  23:         ms.Close();
  24:         return jsonString;
  25:     }
  26:
  27:     /// <summary>
  28:     /// JSON反序列化
  29:     /// </summary>
  30:     public static T JsonDeserialize<T>(string jsonString)
  31:     {
  32:         DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
  33:         MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
  34:         T obj = (T)ser.ReadObject(ms);
  35:         return obj;
  36:     }
  37: }

  序列化Demo:

  简单对象Person:

1: public class Person
  2: {
  3:     public string Name { get; set; }
  4:     public int Age { get; set; }
  5: }

  序列化为JSON字符串:

 

 1: protected void Page_Load(object sender, EventArgs e)
  2: {
  3:     Person p = new Person();
  4:     p.Name = "张三";
  5:     p.Age = 28;
  6:
  7:     string jsonString = JsonHelper.JsonSerializer<Person>(p);
  8:     Response.Write(jsonString);
  9: }

  输出结果:

 {"Age":28,"Name":"张三"}

  反序列化Demo:

 1: protected void Page_Load(object sender, EventArgs e)
  2: {
  3:     string jsonString = "{\"Age\":28,\"Name\":\"张三\"}";
  4:     Person p = JsonHelper.JsonDeserialize<Person>(jsonString);
  5: }

  ASP.NET中的JSON序列化和反序列化还可以使用JavaScriptSerializer,在 System.Web.Script.Serializatioin命名空间下,需引用System.Web.Extensions.dll.也可以使用 JSON.NET.

以上就是.NET中JSON数据进行序列化和反序列化操作分析的详细内容,更多请关注其它相关文章!