javascript
JSON.NET 简单的使用
JSON.NET(http://json.codeplex.com/)使用來(lái)將.NET中的對(duì)象轉(zhuǎn)換為JSON字符串(序列化?),或者將JSON字符串轉(zhuǎn)換為.NET中已有類型的對(duì)象(反序列化?)
首先為了例子隨便定義一個(gè)類型:
public class Product {public string Name { get; set; }public DateTime Expiry { get; set; }public decimal Price { get; set; }public string[] Sizes { get; set; }public override string ToString(){return string.Format("Name:{0},Expiry:{1},Price:{2},SizesCount:{3}", Name, Expiry, Price, Sizes.Length);} }初始化對(duì)象:
public static void Main(string[] passwordargs) {Product product = new Product(){Name = "android",Expiry = DateTime.Now,Price = 2000,Sizes = new string[] { "1.5", "2.2", "4.1" }}; }進(jìn)行到JSON的轉(zhuǎn)換:
Console.WriteLine(JsonConvert.SerializeObject(product));輸出結(jié)果:
{"Name":"android","Expiry":"2013-08-30T09:50:11.5147845+08:00","Price":2000.0,"Sizes":["1.5","2.2","4.1"]}
其它看起來(lái)一切正常,除了這個(gè)日期有點(diǎn)怪
格式化日期:
//設(shè)置日期時(shí)間的格式,與DataTime類型的ToString格式相同 IsoDateTimeConverter iso = new IsoDateTimeConverter(); iso.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";Console.WriteLine(JsonConvert.SerializeObject(product, iso));輸出結(jié)果:
{"Name":"android","Expiry":"2013-08-30 09:53:58","Price":2000.0,"Sizes":["1.5","2.2","4.1"]}
從JSON到對(duì)象的轉(zhuǎn)換:
string str = "{\"Name\":\"android\",\"Expiry\":\"2013-08-30 09:53:58\",\"Price\":2000.0,\"Sizes\":[\"1.5\",\"2.2\",\"4.1\"]}";Product p = (Product)JsonConvert.DeserializeObject(str, typeof(Product));Console.WriteLine(p.ToString());輸出結(jié)果:
Name:android,Expiry:2013/8/30 9:53:58,Price:2000.0,SizesCount:3
從JSON到鍵值對(duì)的轉(zhuǎn)換:
string strJson = @"{""Name1"": ""小明"",""Name2"": ""小花"",""Name3"": ""小紅""}";Dictionary<string, string> _dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(strJson);foreach (KeyValuePair<string, string> kp in _dictionary) {Console.WriteLine(kp.Key + ":" + kp.Value); }輸出結(jié)果:
Name1:小明?
Name2:小花?
Name3:小紅
從字符串轉(zhuǎn)換到JSON對(duì)象,以及JSON對(duì)象的簡(jiǎn)單使用:
string strJson2 = @"{ ""student"": { ""Name1"": ""小明"" , ""Name2"": ""小花"" , ""Name3"": ""小紅""} }";JObject jsonObj = JObject.Parse(strJson2);Console.WriteLine(jsonObj["student"]["Name1"].ToString()); Console.WriteLine(jsonObj["student"]["Name2"].ToString()); Console.WriteLine(jsonObj["student"]["Name3"].ToString());輸出結(jié)果:
小明?
小花?
小紅
直接生成JSON對(duì)象:
JObject json =new JObject(new JProperty("Channel",new JObject(new JProperty("title", "JSON"),new JProperty("link", "JSON.NET"),new JProperty("description", "JSON.NET Description"),new JProperty("items",new JArray(new JObject(new JProperty("haha1", "123")),new JObject(new JProperty("haha2", "456")),new JObject(new JProperty("haha3", "789")))))));Console.WriteLine(json.ToString());輸出結(jié)果:
{?
? "Channel": {?
??? "title": "JSON",?
??? "link": "JSON.NET",?
??? "description": "JSON.NET Description",?
??? "items": [?
????? {?
??????? "haha1": "123"?
????? },?
????? {?
??????? "haha2": "456"?
????? },?
????? {?
??????? "haha3": "789"?
????? }?
??? ]?
? }?
}
?
附上我的實(shí)驗(yàn)代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//解析json字符串
//String str = "{\"h\":\"hello world!\"}";
//JObject obj = JObject.Parse(str);
//Response.Write(obj["h"].ToString());
//Product product = new Product()
//{
// Name = "android",
// Expiry = DateTime.Now,
// Price = 2000,
// Sizes = new string[] { "1.5", "2.2", "4.1" }
//};
//格式化日期
//IsoDateTimeConverter iso = new IsoDateTimeConverter();
//iso.DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff";
//將對(duì)象轉(zhuǎn)換為json格式
//Response.Write(JsonConvert.SerializeObject(product,iso));
//解析匿名對(duì)象
//var obj = new
//{
// Name = "android",
// Expiry = DateTime.Now,
// Price = 2000,
// Sizes = new string[] { "1.5", "2.2", "4.1" }
//};
//格式化日期
//IsoDateTimeConverter iso = new IsoDateTimeConverter();
//iso.DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff";
//Response.Write(JsonConvert.SerializeObject(obj,iso));
//將List轉(zhuǎn)換為json格式
//List<Product> list = new List<Product>() {
// product,product,product,product,product
//};
//格式化日期
//IsoDateTimeConverter iso2 = new IsoDateTimeConverter();
//iso2.DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff";
//Response.Write(JsonConvert.SerializeObject(list,iso2));
//Response.End();
//將DataTable轉(zhuǎn)換為json格式
//DataTable dt = new DataTable();
//dt.Columns.Add("id", typeof(int));
//dt.Columns.Add("name", typeof(string));
//dt.Columns.Add("regtime", typeof(string));
//dt.Rows.Add(new object[] { 1, "張三", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") });
//dt.Rows.Add(new object[] { 2, "李四", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") });
//Response.Write(JsonConvert.SerializeObject(dt));
//Response.End();
//從json到對(duì)象轉(zhuǎn)換
//string str = "{\"Name\":\"android\",\"Expiry\":\"2013-08-30 09:53:58\",\"Price\":2000.0,\"Sizes\":[\"1.5\",\"2.2\",\"4.1\"]}";
//Product pro = (Product)JsonConvert.DeserializeObject(str, typeof(Product));
//Product pro = JsonConvert.DeserializeObject<Product>(str);
//Response.Write(pro.ToString());
//匿名對(duì)象中包含列表對(duì)象等
//var obj = new { productList = list, strHTML = "Welcome!" };
//IsoDateTimeConverter iso3 = new IsoDateTimeConverter();
//iso3.DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff";
//Response.Write(JsonConvert.SerializeObject(obj, iso3));
//Response.End();
?
//Json數(shù)組
JArray array = new JArray();
array.Add("Manual text");
array.Add(new DateTime(2000, 5, 23));
//Json對(duì)象
JObject o = new JObject();
//設(shè)置Json鍵的名字為MyArray,值為array
o["MyArray"] = array;
//調(diào)用ToString方法得到j(luò)son字符串
string json = o.ToString();
Response.Write(json);
Response.End();
// {
// "MyArray": [
// "Manual text",
// "2000-05-23T00:00:00"
// ]
// }
}
}
public class Product
{
public string Name { get; set; }
public DateTime Expiry { get; set; }
public decimal Price { get; set; }
public string[] Sizes { get; set; }
public override string ToString()
{
return string.Format("Name:{0},Expiry:{1},Price:{2},SizesCount:{3}"
, Name, Expiry.ToString("yyyy-MM-dd HH:mm:ss.fff"), Price, Sizes.Length);
}
}
}
轉(zhuǎn)載于:https://www.cnblogs.com/jhxk/articles/4344632.html
總結(jié)
以上是生活随笔為你收集整理的JSON.NET 简单的使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 苹果开发信息 审核
- 下一篇: [Swift] 使用Playground