C# 对象与JSON串互相转换

DoNet2.0 需要借助于Newtonsoft.Json.dll

 1 代码
 2 
 3 using System;
 4 using System.IO;
 5 using System.Text;
 6 using Newtonsoft.Json;
 7 
 8 namespace OfflineAcceptControl.UCTools
 9 {
10     public class JsonTools
11     {
12         // 从一个对象信息生成Json串
13         public static string ObjectToJson(object obj)
14         {
15            return JavaScriptConvert.SerializeObject(obj);
16         }
17         // 从一个Json串生成对象信息
18         public static object JsonToObject(string jsonString, object obj)
19         {
20            return JavaScriptConvert.DeserializeObject(jsonString, obj.GetType());
21         }
22     }
23 }

Donet3.5自带了DLL处理json串

注意引用:System.Runtime.Serialization,System.ServiceModel.Web

 1 代码
 2 
 3 using System;
 4 using System.Collections.Generic;
 5 using System.IO;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Runtime.Serialization;
 9 using System.Runtime.Serialization.Json;
10 
11 namespace CrjIIOfflineAccept.CrjIITools
12 {
13     public class JsonTools
14     {
15         // 从一个对象信息生成Json串
16         public static string ObjectToJson(object obj)
17         {
18            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
19            MemoryStream stream = new MemoryStream();
20            serializer.WriteObject(stream, obj);
21            byte[] dataBytes = new byte[stream.Length];
22            stream.Position = 0;
23            stream.Read(dataBytes, 0, (int)stream.Length);
24            return Encoding.UTF8.GetString(dataBytes);
25         }
26         // 从一个Json串生成对象信息
27         public static object JsonToObject(string jsonString, object obj)
28         {
29            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
30            MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
31            return serializer.ReadObject(mStream);
32         }
33     }
34 }

 

posted @ 2017-03-29 14:36  jeremy1888  阅读(13570)  评论(0编辑  收藏  举报