Json.Net学习笔记(四) Json对象的读写
为了手动读写Json对象,Json.Net提供了JsonReader 和 JsonWriter这两个抽象类及其相应的派生类:
1.JsonTextReader 和 JsonTextWriter
用来读写Json对象的文本,JsonTextWriter 有大量设置去控制Json对象的格式。
测试:
//写操作
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("CPU");
jsonWriter.WriteValue("Intel");
jsonWriter.WritePropertyName("PSU");
jsonWriter.WriteValue("500W");
jsonWriter.WritePropertyName("Drives");
jsonWriter.WriteStartArray();
jsonWriter.WriteValue("DVD read/writer");
jsonWriter.WriteComment("(broken)");
jsonWriter.WriteValue("500 gigabyte hard drive");
jsonWriter.WriteValue("200 gigabype hard drive");
jsonWriter.WriteEndArray();
jsonWriter.WriteEndObject();
}
Console.WriteLine(sb.ToString());
输出结果:
{
"CPU": "Intel",
"PSU": "500W",
"Drives": [
"DVD read/writer"
/*(broken)*/,
"500 gigabyte hard drive",
"200 gigabype hard drive"
]
}
//读操作
TextReader txtReader = new StringReader(sb.ToString());
using (JsonReader jsonReader = new JsonTextReader(txtReader))
{
string readResult = "{\n";
while (jsonReader.Read())
{
if (jsonReader.TokenType == JsonToken.PropertyName)
{
readResult += (string)jsonReader.Value + ":";
}
else if (jsonReader.TokenType == JsonToken.String)
{
readResult += (string)jsonReader.Value + "\n";
}
else if (jsonReader.TokenType == JsonToken.StartArray)
{
readResult += "[\n";
while (jsonReader.Read())
{
if (jsonReader.TokenType == JsonToken.EndArray)
{
readResult = readResult.Remove(readResult.Length - 2, 1);
readResult += "]\n";
break;
}
if (jsonReader.TokenType == JsonToken.String)
readResult += (string)jsonReader.Value + ",\n";
else if (jsonReader.TokenType == JsonToken.Comment)
readResult += "/*" + (string)jsonReader.Value + "*/,\n";
}
}
}
readResult += "}\n";
Console.WriteLine(readResult);
}
2.JTokenReader and JTokenWriter
JTokenReader and JTokenWriter是读写Linq to Json对象的,他们存在于Newtonsoft.Json.Linq名字空间中
JObject o = new JObject(
new JProperty("Name", "ZhangSan"),
new JProperty("BirthDay", new DateTime(1985, 11, 27)));
JsonSerializer serializer = new JsonSerializer();
Person person = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person));
Console.WriteLine(person.Name);//输出ZhangSan