首页 > 代码库 > newtonsoft.json 序列化,反序列化

newtonsoft.json 序列化,反序列化

public class Book
{
  public string BookID { get; set; }
  public DateTime PublishDate { get; set; }
  public decimal Price { get; set; }

  public override string ToString()
  {
    return "ID:" + BookID + "; Date:" + PublishDate.ToShortDateString() + "; Price" + Price.ToString("n");
  }
}

 

 Book bk = new Book() { BookID = "12111", PublishDate = DateTime.Parse("2012-2-1 22:12:11"), Price=433.12M}; Console.WriteLine(JsonConvert.SerializeObject(bk)); string jsonBook = "{‘BookID‘:‘123‘, ‘PublishDate‘:‘2011-1-2‘, ‘Price‘:23.5}"; Book bk1 = JsonConvert.DeserializeObject<Book>(jsonBook); Console.WriteLine(bk1.ToString());

a.

using Newtonsoft.Json;
using System.Text;

StringBuilder sb = new StringBuilder();
string str = "[{ID:‘1‘,Name:‘John‘,Other:[{Age:‘21‘,Sex:‘0‘}]},{ID:‘2‘,Name:‘Good‘,Other:[{Age:‘36‘,Sex:‘1‘}]}]";
JavaScriptArray javascript = (JavaScriptArray)JavaScriptConvert.DeserializeObject(str);

for (int i = 0; i < javascript.Count; i++ )
{
  JavaScriptObject obj = (JavaScriptObject)javascript[i];
  sb.Append("ID:" + obj["ID"].ToString());
  sb.Append("Name:" + obj["Name"].ToString());
  JavaScriptArray json = (JavaScriptArray)obj["Other"];

  for (int j = 0; j < json.Count; j++)

    {
    JavaScriptObject jsonobj = (JavaScriptObject)json[j];
    sb.Append("Age:" + jsonobj["Age"].ToString());
    sb.Append("Sex:" + jsonobj["Sex"].ToString());
  }
}

 

b.

string jsonText = "[{‘a‘:‘aaa‘,‘b‘:‘bbb‘,‘c‘:‘ccc‘},{‘a‘:‘aaa2‘,‘b‘:‘bbb2‘,‘c‘:‘ccc2‘}]";
JsonReader reader = new JsonReader(new StringReader(jsonText));
while (reader.Read())
{
  textBox1.Text += "TokenType = " + reader.TokenType + " ValueType = " + reader.ValueType + " Value = "http://www.mamicode.com/+ reader.Value +"\r\n";

}

c.定义一个对象:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
///Customer 的摘要说明
/// </summary>
public class Customer
{
  //在序列化前后没有变动
  public string a { get; set; }
  //在序列化前后设置和重置
  public string b { get; set; }
  //设置为null,但在序列化后填充
  public string c { get; set; }
  public string Other { get; set; }
  public Customer()
  {
    //
    //TODO: 在此处添加构造函数逻辑
    //
    a = "";
    b = "";
    c = "";
    Other = null;
  }
}

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

string jsonText = "[{‘a‘:‘aaa‘,‘b‘:‘bbb‘,‘c‘:‘ccc‘},{‘a‘:‘aaa2‘,‘b‘:‘bbb2‘,‘c‘:‘ccc2‘}]";
List<Customer> _list = JsonConvert.DeserializeObject<List<Customer>>(jsonText);
Console.WriteLine(_list[1].a);
foreach (Customer c in _list)
{
  Console.WriteLine(c.c);
}