Newtonsoft.Json code

序列化

Product product = new Product();
product.ExpiryDate = new DateTime(2008, 12, 28); JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new JavaScriptDateTimeConverter());
serializer.NullValueHandling = NullValueHandling.Ignore; using (StreamWriter sw = new StreamWriter(@"c:\json.txt"))
using (JsonWriter writer = new JsonTextWriter(sw))
{
serializer.Serialize(writer, product);
// {"ExpiryDate":new Date(1230375600000),"Price":0}
}

JsonReader读Json字符串

string jsonText = @"{""input"" : ""value"", ""output"" : ""result""}";
JsonReader reader = new JsonTextReader(new StringReader(jsonText)); while (reader.Read())
{
Console.WriteLine(reader.TokenType + "\t\t" + reader.ValueType + "\t\t" + reader.Value);
}

JsonWriter写字符串

StringWriter sw = new StringWriter();
JsonWriter writer = new JsonTextWriter(sw); writer.WriteStartObject();
writer.WritePropertyName("input");
writer.WriteValue("value");
writer.WritePropertyName("output");
writer.WriteValue("result");
writer.WriteEndObject();
writer.Flush(); string jsonText = sw.GetStringBuilder().ToString();
Console.WriteLine(jsonText);

使用JObject读写字符串

JObject jo = JObject.Parse(jsonText);
string[] values = jo.Properties().Select(item => item.Value.ToString()).ToArray();

using Newtonsoft.Json;

using Newtonsoft.Json.Linq;

string jsonText = "[{'a':'aaa','b':'bbb','c':'ccc'},{'a':'aaa2','b':'bbb2','c':'ccc2'}]";

JArray ja =(JArray) JsonConvert.DeserializeObject(jsonText);

JObject o = (JObject)ja[1];

Console.WriteLine(o["a"]);

Console.WriteLine(ja[1]["a"]);

JsonSerializer读写对象(基于JsonWriter与JsonReader)

string jsonArrayText1 = "[{'a':'a1','b':'b1'},{'a':'a2','b':'b2'}]";
JArray ja = (JArray)JsonConvert.DeserializeObject(jsonArrayText1);
string ja1a = ja[]["a"].ToString();
//或者
JObject o = (JObject)ja[];
string oa = o["a"].ToString();

嵌套格式

string jsonText = "{\"beijing\":{\"zone\":\"海淀\",\"zone_en\":\"haidian\"}}";
JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText);
string zone = jo["beijing"]["zone"].ToString();
string zone_en = jo["beijing"]["zone_en"].ToString();

自定义类Project

class Project
{
public string Input { get; set; }
public string Output { get; set; }
}
Project p = new Project() { Input = "stone", Output = "gold" };
JsonSerializer serializer = new JsonSerializer();
StringWriter sw = new StringWriter();
serializer.Serialize(new JsonTextWriter(sw), p);
Console.WriteLine(sw.GetStringBuilder().ToString()); StringReader sr = new StringReader(@"{""Input"":""stone"", ""Output"":""gold""}");
Project p1 = (Project)serializer.Deserialize(new JsonTextReader(sr), typeof(Project));
Console.WriteLine(p1.Input + "=>" + p1.Output);

契约方式:使用System.Runtime.Serialization.dll提供的DataContractJsonSerializer或者 JsonReaderWriterFactory实现

Project p = new Project() { Input = "stone", Output = "gold" };
DataContractJsonSerializer serializer = new DataContractJsonSerializer(p.GetType());
string jsonText; using (MemoryStream stream = new MemoryStream())
{
serializer.WriteObject(stream, p);
jsonText = Encoding.UTF8.GetString(stream.ToArray());
Console.WriteLine(jsonText);
} using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonText)))
{
DataContractJsonSerializer serializer1 = new DataContractJsonSerializer(typeof(Project));
Project p1 = (Project)serializer1.ReadObject(ms);
Console.WriteLine(p1.Input + "=>" + p1.Output);
}

这里要注意,这里的Project类和成员要加相关的Attribute:

[DataContract]
class Project
{
[DataMember]
public string Input { get; set; }
[DataMember]
public string Output { get; set; }
}

实用参考:
JSON验证工具:http://jsonlint.com/
JSON简明教程:http://www.w3school.com.cn/json/
Newtonsoft.Json类库下载:http://json.codeplex.com/

上一篇:C# 解析 json Newtonsoft果然强大,代码写的真好


下一篇:Unity 制作RPG地图2(自己控制地图上图标)