如何将C#/.NET 将json字符串格式数据转换成对象
3个回答
推荐于2016-08-12
展开全部
首先你要按JSON的结构定义一个类,类中的变量要用属性的形式
也就是public String XX{get;set;}这样
然后可以参考我下面的代码,是在.NET 4.6下面写的,好像3.5和4.0要用另一个类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
namespace XXX
{
public class clsJson
{
public static T Deserialize<T>(String s) where T : class
{
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(T));
MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(s));
return dataContractJsonSerializer.ReadObject(memoryStream) as T;
}
public static String Serialize<T>(T t) where T : class
{
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(T));
MemoryStream memoryStream = new MemoryStream();
dataContractJsonSerializer.WriteObject(memoryStream, t);
return Encoding.UTF8.GetString(memoryStream.ToArray(), 0, Convert.ToInt32(memoryStream.Length));
}
}
}
也就是public String XX{get;set;}这样
然后可以参考我下面的代码,是在.NET 4.6下面写的,好像3.5和4.0要用另一个类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
namespace XXX
{
public class clsJson
{
public static T Deserialize<T>(String s) where T : class
{
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(T));
MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(s));
return dataContractJsonSerializer.ReadObject(memoryStream) as T;
}
public static String Serialize<T>(T t) where T : class
{
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(T));
MemoryStream memoryStream = new MemoryStream();
dataContractJsonSerializer.WriteObject(memoryStream, t);
return Encoding.UTF8.GetString(memoryStream.ToArray(), 0, Convert.ToInt32(memoryStream.Length));
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询