在.net 4.0 下可以使用:
//
using System.Runtime.Serialization.Json;
<summary>
解析JSON,仿Javascript风格
</summary>
public static class JSON
{
public static T parse<T>( string jsonString)
{
using ( var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
{
return (T) new DataContractJsonSerializer( typeof(T)).ReadObject(ms);
}
}
public static string stringify( object jsonObject)
{
using ( var ms = new MemoryStream())
{
new DataContractJsonSerializer(jsonObject.GetType()).WriteObject(ms, jsonObject);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
<summary>
解析JSON,仿Javascript风格
</summary>
public static class JSON
{
public static T parse<T>( string jsonString)
{
using ( var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
{
return (T) new DataContractJsonSerializer( typeof(T)).ReadObject(ms);
}
}
public static string stringify( object jsonObject)
{
using ( var ms = new MemoryStream())
{
new DataContractJsonSerializer(jsonObject.GetType()).WriteObject(ms, jsonObject);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
}
在.net 以前版本下用JSON.NET
//
Model转JSON
Model m = new Model();
m.city = " beijing ";
m.city_en = " 北京 ";
string json = JsonConvert.SerializeObject(m);
// JSON转Model
Model m = new Model();
m.city = " beijing ";
m.city_en = " 北京 ";
string json = JsonConvert.SerializeObject(m);
// JSON转Model
m= (Model)JsonConvert.DeserializeObject<Model>(str);