// .Net 3.5
namespace Test
{
using System;
using System.Text;
using System.IO;
using System.Xml;
using Test;
using Microshaoft;
public class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
//[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
JsonObject x = new JsonObject();
string json = JsonSerializeHelper.JavaScriptSerialize<JsonObject>(x);
Console.WriteLine(json);
JsonObject y = JsonSerializeHelper.DataContractJsonDeserialize<JsonObject>(json);
Console.WriteLine(y.F1);
jsonObject z = y.F4;
Console.WriteLine("{0},{1},{2}",z.f2 + 10, y.F5[0].f3[1], y.F5[0].f4[0]);
}
}
}
namespace Test
{
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
[DataContract]
public class JsonObject
{
[DataMember]
public string F1 = "AAAAA";
[DataMember]
public int F2 = 100;
[DataMember]
private string _F3 = "BBBB";
public void Test()
{
}
[DataMember]
public jsonObject F4 = new jsonObject();
[DataMember]
public jsonObject[] F5 = new jsonObject[]
{
new jsonObject()
, new jsonObject()
};
}
[DataContract]
public class jsonObject
{
[DataMember]
public string f1 = "测试";
[DataMember]
public int f2 = 10;
[DataMember]
public string[] f3 = new string[]{"测试1","测试"};
[DataMember]
public List<string> f4 = new List<string>();
public jsonObject()
{
f4.Add("测试Tyrannosaurus");
f4.Add("Amargasaurus");
f4.Add("Mamenchisaurus");
f4.Add("Deinonychus");
f4.Add("Compsognathus");
}
}
}
namespace Microshaoft
{
using System;
using System.IO;
using System.Text;
using System.Runtime.Serialization.Json;
//“System.Web.Script.Serialization.JavaScriptSerializer.JavaScriptSerializer()”已过时:
//“The recommended alternative is System.Runtime.Serialization.DataContractJsonSerializer.”
using System.Web.Script.Serialization;
public static class JsonSerializeHelper
{
public static string DataContractJsonSerialize<T>(T jsonObject)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, jsonObject);
string json = Encoding.UTF8.GetString(ms.GetBuffer());
ms.Close();
ms.Dispose();
ms = null;
return json;
}
public static T DataContractJsonDeserialize<T>(string json)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
T jto = (T) serializer.ReadObject(ms);
ms.Close();
ms.Dispose();
ms = null;
return jto;
}
public static string JavaScriptSerialize<T>(T jsonObject)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
serializer.Serialize(jsonObject, sb);
return sb.ToString();
}
public static T JavaScriptDeserialize<T>(string json)
{
return (T) new JavaScriptSerializer().Deserialize<T>(json);
}
}
}