码迷,mamicode.com
首页 > Web开发 > 详细

newtonsoft.json 序列化,反序列化

时间:2014-08-21 09:38:14      阅读:265      评论:0      收藏:0      [点我收藏+]

标签:des   java   os   io   for   ar   cti   line   

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 = " + 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);
}

 

newtonsoft.json 序列化,反序列化,布布扣,bubuko.com

newtonsoft.json 序列化,反序列化

标签:des   java   os   io   for   ar   cti   line   

原文地址:http://www.cnblogs.com/vihone/p/3926389.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!