• C#将对象转换成JSON字符串,Newtonsoft.Json (JSON.NET)


    官方API说明文档

    http://www.newtonsoft.com/json/help/html/N_Newtonsoft_Json.htm

    http://www.newtonsoft.com/

    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		ValueType		Value");
     
    while (reader.Read())
    {
         Console.WriteLine(reader.TokenType + "		" + WriteValue(reader.ValueType) + "		" + 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'}]

  • 相关阅读:
    榫卯游戏介绍
    如果你有一个域名,你也可以免费有一个diy@yourdomain.com的企业邮局
    封装一个axios请求后台的通用方法
    javascript判断两个对象属性以及值是否相等
    遍历出文档内所有元素的tagName
    windows下nginx的安装及使用方法入门
    css样式重置样式
    canvas绘图
    表单脚本
    javascript事件
  • 原文地址:https://www.cnblogs.com/zouhao/p/6264675.html
Copyright © 2020-2023  润新知