zoukankan      html  css  js  c++  java
  • Newtonsoft.Json序列化和反序列

    摘自http://www.cnblogs.com/sbxwylt/archive/2008/12/31/1366199.html

    Newtonsoft.Json序列化和反序列

    这里下载:http://json.codeplex.com/

    安装:
       1.解压下载文件,得到Newtonsoft.Json.dll
       2.在项目中添加引用..
     序列化和反序列在.net项目中:
     

    Product product = new Product();
     
    product.Name = "Apple";
    product.Expiry = new DateTime(2008, 12, 28);
    product.Price = 3.99M;
    product.Sizes = new string[] { "Small", "Medium", "Large" };
     
    string output = javascriptConvert.SerializeObject(product);
    //{
    //  "Name": "Apple",
    //  "Expiry": new Date(1230422400000),
    //  "Price": 3.99,
    //  "Sizes": [
    //    "Small",
    //    "Medium",
    //    "Large"
    //  ]
    //}
     
    Product deserializedProduct = (Product)javascriptConvert.DeserializeObject(output, typeof(Product));

     
    读取JSON

    string jsonText = "['JSON!',1,true,{property:'value'}]";
     
    JsonReader reader = new JsonReader(new StringReader(jsonText));
     
    Console.WriteLine("TokenType\t\tValueType\t\tValue");
     
    while (reader.Read())
    {
        Console.WriteLine(reader.TokenType + "\t\t" + WriteValue(reader.ValueType) + "\t\t" + WriteValue(reader.Value))
    }


    结果显示:

    TokenTypeValueTypeValue
    StartArray null null
    String System.String JSON!
    Integer System.Int32 1
    Boolean System.Boolean True
    StartObject null null
    PropertyName System.String property
    String System.String value
    EndObject null null
    EndArray null null

    JSON写入

    StringWriter sw = new StringWriter();
    JsonWriter writer = new JsonWriter(sw);
     
    writer.WriteStartArray();
    writer.WriteValue("JSON!");
    writer.WriteValue(1);
    writer.WriteValue(true);
    writer.WriteStartObject();
    writer.WritePropertyName("property");
    writer.WriteValue("value");
    writer.WriteEndObject();
    writer.WriteEndArray();
     
    writer.Flush();
     
    string jsonText = sw.GetStringBuilder().ToString();
     
    Console.WriteLine(jsonText);
    // ['JSON!',1,true,{property:'value'}]


    这里会打印出: ['JSON!',1,true,{property:'value'}].

  • 相关阅读:
    1 python 基础
    php数据几行代码导出到excel(非插件)
    支付宝单笔转账demo (改配置直接用)
    require include 一个隐藏的用法:作用域。
    require include php5中最新区别,百度上好多错的。
    MySQL 普通注册插入优化。
    nginx 下开启pathinfo模式
    微信网页授权demo2
    事务处理不支持的可能程序外问题。
    php5.3中namespace的说明,帮助初次接触namespace的phper快速理解
  • 原文地址:https://www.cnblogs.com/nygfcn1234/p/3110883.html
Copyright © 2011-2022 走看看