首页 > 代码库 > (转)JavaScriptSerializer,DataContractJsonSerializer解析JSON字符串功能小记
(转)JavaScriptSerializer,DataContractJsonSerializer解析JSON字符串功能小记
JsonAbout:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web.Script.Serialization;
using System.Runtime.Serialization.Json;
namespace ConsoleApplicationTest
{
public class JsonAbout
{
public static T Json2ModelJS<T>(string JsonStr)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
T userJson = jss.Deserialize<T>(JsonStr);
return userJson;
}
public static string Model2JsonJS<T>(T model)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
string userJson = jss.Serialize(model);
return userJson;
}
public static T Json2Model<T>(string jsonString)
{
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
{
return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms);
}
}
public static string Model2Json<T>(T jsonObject)
{
using (var ms = new MemoryStream())
{
new DataContractJsonSerializer(typeof(T)).WriteObject(ms, jsonObject);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
}
}
测试类:
public class JsonModelDemo
{
public void Show()
{
string jsonA = "{\"IDA\":1,\"NameA\":\"A\",\"B\":{\"IDB\":2,\"NameB\":\"B\"}}";
string jsonB = "{\"Msg\":\"Test\",\"Data\":{\"IDA\":1,\"NameA\":\"A\",\"B\":[{\"IDB\":2,\"NameB\":\"B1\"},{\"IDB\":3,\"NameB\":\"B2\"}]}}";
Console.WriteLine("DataContractJsonSerializer:");
A a1 = JsonAbout.Json2Model<A>(jsonA);
B b1 = JsonAbout.Json2Model<B>(jsonA);
A a2 = JsonAbout.Json2Model<A>(jsonB);
B b2 = JsonAbout.Json2Model<B>(jsonB);
Output(a1);
Output(b1);
Output(a2);
Output(b2);
Console.WriteLine("JavaScriptSerializer:");
A a3 = JsonAbout.Json2ModelJS<A>(jsonA);
B b3 = JsonAbout.Json2ModelJS<B>(jsonA);
A a4 = JsonAbout.Json2ModelJS<A>(jsonB);
B b4 = JsonAbout.Json2ModelJS<B>(jsonB);
Output(a3);
Output(b3);
Output(a4);
Output(b4);
}
private void Output(A a)
{
Console.WriteLine("IDA:"+a.IDA + ", NameA:" + a.NameA);
if (a.b != null)
{
Console.WriteLine("B:"+a.b.IDB+","+a.b.NameB);
}
}
private void Output(B b)
{
Console.WriteLine("IDB:" + b.IDB + ", NameB:" + b.NameB);
}
}
public class A
{
public int IDA { get; set; }
public string NameA { get; set; }
public B b { get; set; }
}
public class B
{
public int IDB { get; set; }
public string NameB { get; set; }
}
输出:
DataContractJsonSerializer:
IDA:1, NameA:A
IDB:0, NameB:
IDA:0, NameA:
IDB:0, NameB:
JavaScriptSerializer:
IDA:1, NameA:A
B:2,B
IDB:0, NameB:
IDA:0, NameA:
IDB:0, NameB:
结论:JavaScriptSerializer可以识别关联的实体,其他的待验证。
转: http://artwl.cnblogs.com
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。