在.NET中使用Newtonsoft.Json转换,读取,写入.

前端之家收集整理的这篇文章主要介绍了在.NET中使用Newtonsoft.Json转换,读取,写入.前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

using Newtonsoft.Json;

using Newtonsoft.Json.Converters;

//把Json字符串反序列化为对象

目标对象 = JavaScriptConvert.DeserializeObject(JSON字符串,typeof(目标对象));

//把目标对象序列化为Json字符串

string Json字符串 = JavaScriptConvert.SerializeObject(目标对象);

1.引用Newtonsoft.Json.dll

2.在项目中添加引用..

一、序列化和反序列在.net项目中:

using Newtonsoft.Json;

using Newtonsoft.Json.Converters;

public partial class aaaa : System.Web.UI.Page

{

protected void Page_Load(object sender,EventArgs e)

{

Product product = new Product();

product.Name = "Apple";

product.Expiry = new DateTime(2008,12,28);

product.Sizes = new string[] { "Small","Medium","Large" };

string output = JavaScriptConvert.SerializeObject(product); //序列化JavaScriptConvert.SerializeObject

Response.Write(output);

//输出:{"Name":"Apple","Expiry":new Date(1230422400000),"Sizes":["Small","Large"]}

Product deserializeObject = (Product)JavaScriptConvert.DeserializeObject(output,typeof(Product));

//反序列化 JavaScriptConvert.DeserializeObject

Response.Write(deserializeObject.Expiry);

//输出:2008-12-28 00:00:00

}

}

public class Product

{

String _Name;

public String Name

{

get { return _Name; }

set { _Name = value; }

}

DateTime _Expiry;

public DateTime Expiry

{

get { return _Expiry; }

set { _Expiry = value; }

}

String[] _Sizes;

public String[] Sizes

{

get { return _Sizes; }

set { _Sizes = value; }

}

}

二、读取JSON

using Newtonsoft.Json;

using Newtonsoft.Json.Converters;

using System.IO;

public partial class aaaa : System.Web.UI.Page

{

protected void Page_Load(object sender,EventArgs e)

{

string jsonText = "['JSON!',1,true,{property:'value'}]";

JsonReader reader = new JsonReader(new StringReader(jsonText));

Response.Write("<table border=1><tr><th>TokenType</th><th>ValueType</th><th>Value</th></tr>");

while (reader.Read())

{

Response.Write("<tr><td>" + reader.TokenType + "</td><td>" + reader.ValueType + "</td><td>" + reader.Value + "</td></tr>");

}

Response.Write("</table>");

}

}

三、JSON写入

using Newtonsoft.Json;

using Newtonsoft.Json.Converters;

using System.IO;

public partial class aaaa : System.Web.UI.Page

{

protected void Page_Load(object sender,EventArgs e)

{

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();

Response.Write(jsonText);

//输出:["JSON!",{"property":"value"}]

}

}

原文链接:https://www.f2er.com/json/290771.html

猜你在找的Json相关文章