zoukankan      html  css  js  c++  java
  • vs2005中使用Newtonsoft.Json.dll操作json

    、说明:
    很多情况下,我们需要把数据类型做一些转换,供其它外部的子系统调用。最为典型的是生成json格式供javascript作调用。
    现成的组件Newtonsoft.Json可以实现object2json之间的转换。
     
    二、使用
    安装:
    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))
    }

    结果显示:
    TokenType ValueType Value
    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'}]. Newtonsoft.Json.dll 使用 - 水滴石穿 - 水滴石穿
  • 相关阅读:
    Unity3D Editor模式下批量修改prefab
    3D touch在Unity3D中的使用
    Unity中的协程是什么?
    Unity3D脚本调用Objective C代码实现游戏内购买
    WindowsPhone8拍照功能实现简介
    WindowsPhone App如何扩展能够使用的内存
    SVN 提交代码时提示文件已经存在解决办法
    iOS检查App新版本并更新新版本
    iOS存储数据字典到沙盒
    统计整个Xcode工程代码行数
  • 原文地址:https://www.cnblogs.com/zhuawang/p/2071258.html
Copyright © 2011-2022 走看看