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可以识别关联的实体,其他的待验证。




本文转自Artwl博客园博客,原文链接:http://www.cnblogs.com/artwl/,如需转载请自行联系原作者

上一篇:oracle数据库是归档模式


下一篇:如何生成RSA2密钥