快速入门
JSON与对象间的相互映射
为了能在.NET程序中使用JSON格式的数据,我们首先能想到的方法是使用JSON文本去填充特定类别的新实例;或者用一种传统的方法去构建与输入的JSON文本相对应的数据结构,再或者用创建字典这种更为普遍的方法。
相反,一个简单的输出操作可能更加适合,使用对象中存储的数据来生成新的JSON字符串。
基于这种目的,litjson中包含了一个jsonmapper类,该类别为实现json到对象和对象到json转化提供了两种主要方法:JsonMapper.ToObject 和 JsonMapper.ToJson.
简单的JsonMapper 案例
如下列案例所示,ToObject 中有一个“JsonMapper.ToObject”的重载方法,可以用来指定返回的对象类型。
using LitJson;
using System;
public class Person
{
// C# 3.0 auto-implemented properties
public string Name { get; set; }
public int Age { get; set; }
public DateTime Birthday { get; set; }
}
public class JsonSample
{
public static void Main()
{
PersonToJson();
JsonToPerson();
}
public static void PersonToJson()
{
Person bill = new Person();
bill.Name = "William Shakespeare";
bill.Age = 51;
bill.Birthday = new DateTime(1564, 4, 26);
string json_bill = JsonMapper.ToJson(bill);
Console.WriteLine(json_bill);
}
public static void JsonToPerson()
{
string json = @"
{
""Name"" : ""Thomas More"",
""Age"" : 57,
""Birthday"" : ""02/07/1478 00:00:00""
}";
Person thomas = JsonMapper.ToObject<Person>(json);
Console.WriteLine("Thomas' age: {0}", thomas.Age);
}
}
案例输出:
{"Name":"William Shakespeare","Age":51,"Birthday":"04/26/1564 00:00:00"}
Thomas' age: 57
使用不带类型的JsonMapper.ToObject
当JSON文件将被读取,而与对应数据结构相匹配的类并不可用或者格式不对时,用户可以使用不带类型的toobject方法。该方法返回一个JsonData实例。JsonData 是一个通用的目标格式,它支持包括链表和字典在内所有的JSON的数据格式。
using LitJson;
using System;
public class JsonSample
{
public static void Main()
{
string json = @"
{
""album"" : {
""name"" : ""The Dark Side of the Moon"",
""artist"" : ""Pink Floyd"",
""year"" : 1973,
""tracks"" : [
""Speak To Me"",
""Breathe"",
""On The Run""
]
}
}
";
LoadAlbumData(json);
}
public static void LoadAlbumData(string json_text)
{
Console.WriteLine("Reading data from the following JSON string: {0}",
json_text);
JsonData data = JsonMapper.ToObject(json_text);
// Dictionaries are accessed like a hash-table
Console.WriteLine("Album's name: {0}", data["album"]["name"]);
// Scalar elements stored in a JsonData instance can be cast to
// their natural types
string artist = (string) data["album"]["artist"];
int year = (int) data["album"]["year"];
Console.WriteLine("Recorded by {0} in {1}", artist, year);
// Arrays are accessed like regular lists as well
Console.WriteLine("First track: {0}", data["album"]["tracks"][0]);
}
}
案例输出:
Reading data from the following JSON string:
{
"album" : {
"name" : "The Dark Side of the Moon",
"artist" : "Pink Floyd",
"year" : 1973,
"tracks" : [
"Speak To Me",
"Breathe",
"On The Run"
]
}
}
Album's name: The Dark Side of the Moon
Recorded by Pink Floyd in 1973
First track: Speak To Me