.net已经集成了json解析,类名叫DataContractJsonSerializer
class="selflink">DataContractJsonSerializer 类型公开以下成员。
名称说明 DataContractJsonSerializer(Type) instance of the <span class="selflink">DataContractJsonSerializer class to serialize or deserialize an object of the specified type. ">初始化 DataContractJsonSerializer 类的新实例,以便序列化或反序列化指定类型的对象。 DataContractJsonSerializer(Type, IEnumerable<Type>) 初始化 DataContractJsonSerializer 类的新实例,以便序列化或反序列化指定类型的对象以及可在对象图中呈现的已知类型的集合。可以使用 DataContractJsonSerializer 类将类型实例序列化为 JSON 文档,并将 JSON 文档反序列化为类型实例。 can create a type named <span class="code">Person with properties that contain essential data, such as a name and address.">例如,可以使用包含重要数据(如名称和地址)的属性创建一个名为 Person 的类型。 然后,可以创建和操作一个 Person 类实例,并在 JSON 文档中写入所有其属性值以便于以后检索。 可随后将该 JSON 文档反序列化为 Person 类,或者反序列化为另一个具有等效数据协定的类。
namespace SL_DataContractJsonSerializer { public partial class Page : UserControl { public Page() { InitializeComponent(); } //This uses an event handler, not SL data binding void OnClick(object sender, EventArgs args) { txtOutput1.Text = "Create a User object and serialize it."; string json = WriteFromObject(); txtOutput2.Text = json.ToString(); // Displays: {"Age":42,"Name":"Bob"} txtOutput3.Text = "Deserialize the data to a User object."; string jsonString = "{'Name':'Bill', 'Age':53}"; User deserializedUser = ReadToObject(jsonString); txtOutput4.Text = deserializedUser.Name; // Displays: Bill txtOutput5.Text = deserializedUser.Age.ToString(); // Displays: 53 } // Create a User object and serialize it to a JSON stream. public static string WriteFromObject() { //Create User object. User user = new User("Bob", 42); //Create a stream to serialize the object to. MemoryStream ms = new MemoryStream(); // Serializer the User object to the stream. DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(User)); ser.WriteObject(ms, user); byte[] json = ms.ToArray(); ms.Close(); return Encoding.UTF8.GetString(json, 0, json.Length); } // Deserialize a JSON stream to a User object. public static User ReadToObject(string json) { User deserializedUser = new User(); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)); DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedUser.GetType()); deserializedUser = ser.ReadObject(ms) as User; ms.Close(); return deserializedUser; } } [DataContract] public class User { [DataMember] public string Name { get; set; } [DataMember] public int Age { get; set; } public User() { } public User(string newName, int newAge) { Name = newName; Age = newAge; } } }