json序列化和发序列化

本文介绍了一个用于处理JSON序列化与反序列化的实用工具类JsonHelper,其中包括了将对象转换为JSON字符串的方法及从JSON字符串中读取对象的方法。这些方法利用DataContractJsonSerializer实现,适用于.NET平台。
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Runtime.Serialization.Json;
 6 using System.IO;
 7 
 8 namespace Dtsc.WorkFlow
 9 {
10     public class JsonHelper
11     {
12         public static object GetObjectListByJsonText(Type t,string jsonText)
13         {
14             object obj = null;
15             DataContractJsonSerializer ser1 = new DataContractJsonSerializer(t);          
16             using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonText)))
17             {
18                 obj = ser1.ReadObject(ms);
19             }
20             return obj;
21         }
22 
23         /// <summary>
24         /// 返回序列化Json字符串
25         /// </summary>
26         /// <typeparam name="T"></typeparam>
27         /// <param name="TObject">需转换对象,注意:需转换对象必须标注[Serializable]特性,对象属性必须标注[Serializable]特性</param>
28         /// <returns></returns>
29         public static string GetJsonString<T>(T TObject)
30         {
31             DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
32             using (MemoryStream ms = new MemoryStream())
33             {
34                 serializer.WriteObject(ms, TObject);
35                 string ss = Encoding.UTF8.GetString(ms.GetBuffer());
36                 return ss.Replace("\0", "");
37             }
38         }
39 
40         /// <summary>
41         /// 将Json字符串转换成相应对象。
42         /// </summary>
43         /// <typeparam name="T"></typeparam>
44         /// <param name="json">Json字符串</param>
45         /// <returns></returns>
46         public static T ReturnJsonObject<T>(string json)
47         {
48             DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
49             using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
50             {
51                 return (T)serializer.ReadObject(ms);
52             }
53         }
54     }
55 }

 

转载于:https://www.cnblogs.com/caicheng/archive/2012/07/27/2611427.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值