本文以一个简单的小例子,简述Json.Net的相关知识,仅供学习分享使用,如有不足之处,还请指正。
概述
Json.Net is a Popular high-performance JSON framework for .NET.
Json.Net是当前比较流行的高效的Json解析的.Net框架。主要支持序列化,反序列化,手动解析,Linq等功能,可谓是功能强大而使用简单。
- 使用方式:在项目中引入Newtonsoft.Json.dll文件即可里面的功能。
- 常见功能:序列化与反序列化
- 常用的类:JsonConvert,JsonSerializerSettings,JValue , JArray , JObject , Formatting , JTokenWriter , JToken
效果图
具体如下图所示【序列化和反序列化】:
核心代码
序列化和反序列化的代码如下
public partial class JsonForm : Form
{
public JsonForm()
{
InitializeComponent();
} /// <summary>
/// 序列化对象
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSerializeObject_Click(object sender, EventArgs e)
{
Person p = new Person()
{
Name = "Hexiang",
Birthday = DateTime.Parse("2017-02-20 14:30:00"),
Gender = "男",
Love = "Ball"
};
string strJson = JsonConvert.SerializeObject(p, Formatting.Indented);
this.txtJson.Text = strJson;
} /// <summary>
/// 序列化字典
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSerializeDictionary_Click(object sender, EventArgs e)
{
Dictionary<string, int> dicPoints = new Dictionary<string, int>(){
{ "James", },
{ "Jo", },
{ "Jess", }
}; string strJson = JsonConvert.SerializeObject(dicPoints, Formatting.Indented); this.txtJson.Text = strJson; } /// <summary>
/// 序列化List
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSerializeList_Click(object sender, EventArgs e)
{
List<string> lstGames = new List<string>()
{
"Starcraft",
"Halo",
"Legend of Zelda"
}; string strJson = JsonConvert.SerializeObject(lstGames); this.txtJson.Text = strJson;
} /// <summary>
/// 序列化到文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSerializeToFile_Click(object sender, EventArgs e)
{
Person p = new Person()
{
Name = "Hexiang",
Birthday = DateTime.Parse("2017-02-20 14:30:00"),
Gender = "男",
Love = "Ball"
};
using (StreamWriter file = File.CreateText(@"d:\person.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, p);
}
} /// <summary>
/// 序列化枚举
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSerializeEnum_Click(object sender, EventArgs e)
{
List<StringComparison> stringComparisons = new List<StringComparison>
{
StringComparison.CurrentCulture,
StringComparison.Ordinal
}; string jsonWithoutConverter = JsonConvert.SerializeObject(stringComparisons); this.txtJson.Text = jsonWithoutConverter;//序列化出来是枚举所代表的整数值 string jsonWithConverter = JsonConvert.SerializeObject(stringComparisons, new StringEnumConverter());
this.txtJson.Text += "\r\n";
this.txtJson.Text += jsonWithConverter;//序列化出来是枚举所代表的文本值
// ["CurrentCulture","Ordinal"] List<StringComparison> newStringComparsions = JsonConvert.DeserializeObject<List<StringComparison>>(
jsonWithConverter,
new StringEnumConverter());
} /// <summary>
/// 序列化DataSet
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSerializeDataSet_Click(object sender, EventArgs e)
{
DataSet dataSet = new DataSet("dataSet");
dataSet.Namespace = "NetFrameWork";
DataTable table = new DataTable();
DataColumn idColumn = new DataColumn("id", typeof(int));
idColumn.AutoIncrement = true; DataColumn itemColumn = new DataColumn("item");
table.Columns.Add(idColumn);
table.Columns.Add(itemColumn);
dataSet.Tables.Add(table); for (int i = ; i < ; i++)
{
DataRow newRow = table.NewRow();
newRow["item"] = "item " + i;
table.Rows.Add(newRow);
} dataSet.AcceptChanges(); string json = JsonConvert.SerializeObject(dataSet, Formatting.Indented);
this.txtJson.Text = json;
} /// <summary>
/// 序列化JRaw
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSerializeRaw_Click(object sender, EventArgs e)
{
JavaScriptSettings settings = new JavaScriptSettings
{
OnLoadFunction = new JRaw("OnLoad"),
OnUnloadFunction = new JRaw("function(e) { alert(e); }")
}; string json = JsonConvert.SerializeObject(settings, Formatting.Indented); this.txtJson.Text = json; } /// <summary>
/// 反序列化List
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDeserializeList_Click(object sender, EventArgs e)
{
string json = @"['Starcraft','Halo','Legend of Zelda']";
List<string> videogames = JsonConvert.DeserializeObject<List<string>>(json);
this.txtJson.Text = string.Join(", ", videogames.ToArray());
} /// <summary>
/// 反序列化字典
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDeserializeDictionary_Click(object sender, EventArgs e)
{
string json = @"{
'href': '/account/login.aspx',
'target': '_blank'
}"; Dictionary<string, string> dicAttributes = JsonConvert.DeserializeObject<Dictionary<string, string>>(json); this.txtJson.Text = dicAttributes["href"];
this.txtJson.Text += "\r\n";
this.txtJson.Text += dicAttributes["target"]; } /// <summary>
/// 反序列化匿名类
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDeserializeAnaymous_Click(object sender, EventArgs e)
{
var definition = new { Name = "" }; string json1 = @"{'Name':'James'}";
var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);
this.txtJson.Text = customer1.Name;
this.txtJson.Text += "\r\n"; string json2 = @"{'Name':'Mike'}";
var customer2 = JsonConvert.DeserializeAnonymousType(json2, definition);
this.txtJson.Text += customer2.Name; } /// <summary>
/// 反序列化DataSet
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDeserializeDataSet_Click(object sender, EventArgs e)
{
string json = @"{
'Table1': [
{
'id': 0,
'item': 'item 0'
},
{
'id': 1,
'item': 'item 1'
}
]
}"; DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(json); DataTable dataTable = dataSet.Tables["Table1"];
this.txtJson.Text = dataTable.Rows.Count.ToString(); foreach (DataRow row in dataTable.Rows)
{
this.txtJson.Text += "\r\n";
this.txtJson.Text += (row["id"] + " - " + row["item"]);
} } /// <summary>
/// 从文件反序列化
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDeserializeFrmFile_Click(object sender, EventArgs e)
{
using (StreamReader file = File.OpenText(@"d:\person.json"))
{
JsonSerializer serializer = new JsonSerializer();
Person p = (Person)serializer.Deserialize(file, typeof(Person));
this.txtJson.Text = p.Name;
}
} /// <summary>
/// 反序列化带构造函数人类
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDeserializeConstructor_Click(object sender, EventArgs e)
{
string json = @"{'Url':'http://www.google.com'}"; //直接序列化会报错,需要设置JsonSerializerSettings中ConstructorHandling才可以。
Website website = JsonConvert.DeserializeObject<Website>(json, new JsonSerializerSettings
{
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
}); this.txtJson.Text = website.Url; } /// <summary>
/// 反序列化对象,如果有构造函数中,创建对象,则用Json的进行替换
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDeserializeObjectCreation_Click(object sender, EventArgs e)
{
//
string json = @"{
'Name': 'James',
'Offices': [
'Auckland',
'Wellington',
'Christchurch'
]
}"; UserViewModel model1 = JsonConvert.DeserializeObject<UserViewModel>(json); this.txtJson.Text = string.Join(",", model1.Offices);//默认会重复
this.txtJson.Text += "\r\n"; //每次从Json中创建新的对象
UserViewModel model2 = JsonConvert.DeserializeObject<UserViewModel>(json, new JsonSerializerSettings
{
ObjectCreationHandling = ObjectCreationHandling.Replace
}); this.txtJson.Text = string.Join(",", model2.Offices); } /// <summary>
/// 序列化默认值处理,没有赋值的则不序列化出来
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSerializeDefautValue_Click(object sender, EventArgs e)
{
Person person = new Person(); string jsonIncludeDefaultValues = JsonConvert.SerializeObject(person, Formatting.Indented); this.txtJson.Text=(jsonIncludeDefaultValues);//默认的序列化,带不赋值的属性 this.txtJson.Text += "\r\n"; string jsonIgnoreDefaultValues = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
{
DefaultValueHandling = DefaultValueHandling.Ignore //去掉不赋值的属性
}); this.txtJson.Text+=(jsonIgnoreDefaultValues);
} /// <summary>
/// 如果实体类中没有对应属性,则如何处理
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDeserializeMissingMember_Click(object sender, EventArgs e)
{
string json = @"{
'FullName': 'Dan Deleted',
'Deleted': true,
'DeletedDate': '2013-01-20T00:00:00'
}"; try
{
JsonConvert.DeserializeObject<Account>(json, new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Error //要么忽略,要么报错
});
}
catch (JsonSerializationException ex)
{
this.txtJson.Text=(ex.Message);
// Could not find member 'DeletedDate' on object of type 'Account'. Path 'DeletedDate', line 4, position 23.
}
} /// <summary>
/// 序列化时Null值的处理
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSerializeNull_Click(object sender, EventArgs e)
{
Person person = new Person
{
Name = "Nigal Newborn"
}; //默认的序列化
string jsonIncludeNullValues = JsonConvert.SerializeObject(person, Formatting.Indented); this.txtJson.Text=(jsonIncludeNullValues);
this.txtJson.Text += "\r\n"; //去掉Null值的序列化
string jsonIgnoreNullValues = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore //可以忽略,可以包含
}); this.txtJson.Text+=(jsonIgnoreNullValues); } /// <summary>
/// 序列化日期格式
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSerializeDateTime_Click(object sender, EventArgs e)
{
DateTime mayanEndOfTheWorld = new DateTime(, , ); string jsonIsoDate = JsonConvert.SerializeObject(mayanEndOfTheWorld); this.txtJson.Text = (jsonIsoDate); this.txtJson.Text += "\r\n";
string jsonMsDate = JsonConvert.SerializeObject(mayanEndOfTheWorld, new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
}); this.txtJson.Text += (jsonMsDate);
// "\/Date(1356044400000+0100)\/"
this.txtJson.Text += "\r\n";
string json = JsonConvert.SerializeObject(mayanEndOfTheWorld, new JsonSerializerSettings
{
DateFormatString = "yyyy-MM-dd",
Formatting = Formatting.Indented
});
this.txtJson.Text += json;
} private void btnSerializeDateZone_Click(object sender, EventArgs e)
{
Flight flight = new Flight
{
Destination = "Dubai",
DepartureDate = new DateTime(, , , , , , DateTimeKind.Unspecified),
DepartureDateUtc = new DateTime(, , , , , , DateTimeKind.Utc),
DepartureDateLocal = new DateTime(, , , , , , DateTimeKind.Local),
Duration = TimeSpan.FromHours(5.5)
}; string jsonWithRoundtripTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind
}); this.txtJson.Text=(jsonWithRoundtripTimeZone);
this.txtJson.Text += "\r\n";
string jsonWithLocalTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Local
}); this.txtJson.Text+=(jsonWithLocalTimeZone);
this.txtJson.Text += "\r\n"; string jsonWithUtcTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Utc
}); this.txtJson.Text += (jsonWithUtcTimeZone);
this.txtJson.Text += "\r\n"; string jsonWithUnspecifiedTimeZone = JsonConvert.SerializeObject(flight, Formatting.Indented, new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Unspecified
}); this.txtJson.Text += (jsonWithUnspecifiedTimeZone); } private void btnSerializeDataContract_Click(object sender, EventArgs e)
{
CFile file = new CFile
{
Id = Guid.NewGuid(),
Name = "ImportantLegalDocuments.docx",
Size = *
}; string json = JsonConvert.SerializeObject(file, Formatting.Indented); this.txtJson.Text=(json);
} /// <summary>
/// 序列化默认设置
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSerializeDefaultSetting_Click(object sender, EventArgs e)
{
// settings will automatically be used by JsonConvert.SerializeObject/DeserializeObject
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented,
ContractResolver = new CamelCasePropertyNamesContractResolver()
}; Person s = new Person()
{
Name = "Eric",
Birthday = new DateTime(, , , , , , DateTimeKind.Utc),
Gender = "男",
Love = "Web Dude"
}; string json = JsonConvert.SerializeObject(s);
this.txtJson.Text = json;
} /// <summary>
/// 序列化Immutable
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSerializeImmutable_Click(object sender, EventArgs e)
{
//ImmutableList<string> l = ImmutableList.CreateRange(new List<string>
// {
// "One",
// "II",
// "3"
// }); //string json = JsonConvert.SerializeObject(l, Formatting.Indented); } /// <summary>
/// 序列化JsonProperty
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSerializeJsonProperty_Click(object sender, EventArgs e)
{
Videogame starcraft = new Videogame
{
Name = "Starcraft",
ReleaseDate = new DateTime(, , )
}; string json = JsonConvert.SerializeObject(starcraft, Formatting.Indented); this.txtJson.Text = json;
} /// <summary>
/// 序列化排序,值越小,月靠前,默认是0
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSerializeOrder_Click(object sender, EventArgs e)
{
Account0 account = new Account0
{
FullName = "Aaron Account",
EmailAddress = "aaron@example.com",
Deleted = true,
DeletedDate = new DateTime(, , ),
UpdatedDate = new DateTime(, , ),
CreatedDate = new DateTime(, , )
}; string json = JsonConvert.SerializeObject(account, Formatting.Indented); this.txtJson.Text=(json); } private void btnSerializeJsonConstructor_Click(object sender, EventArgs e)
{
string json = @"{
""UserName"": ""domain\\username"",
""Enabled"": true
}"; User user = JsonConvert.DeserializeObject<User>(json); this.txtJson.Text=(user.UserName); } private void btnSerializeJsonIgnore_Click(object sender, EventArgs e)
{
Account1 account = new Account1
{
FullName = "Joe User",
EmailAddress = "joe@example.com",
PasswordHash = "VHdlZXQgJ1F1aWNrc2lsdmVyJyB0byBASmFtZXNOSw=="
}; string json = JsonConvert.SerializeObject(account);
this.txtJson.Text = json;
} /// <summary>
/// 其他功能
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnOtherFunction_Click(object sender, EventArgs e)
{
JsonForm1 jsonOther = new JsonForm1();
jsonOther.ShowDialog();
}
}
其他功能
具体如下图所示【其他功能】:
其他功能代码如下
public partial class JsonForm1 : Form
{
public JsonForm1()
{
InitializeComponent();
} /// <summary>
/// 手动创建Json
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCreateJsonManually_Click(object sender, EventArgs e)
{
JArray array = new JArray();
array.Add("Manual text");
array.Add(new DateTime(, , )); JObject o = new JObject();
o["MyArray"] = array; string json = o.ToString();
this.txtJson.Text = json; } /// <summary>
/// 列表创建Json
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCollectionJson_Click(object sender, EventArgs e)
{
JObject o = new JObject()
{
{ "Cpu", "Intel" },
{ "Memory", },
{
"Drives", new JArray
{
"DVD",
"SSD"
}
}
}; this.txtJson.Text = o.ToString();
} private void btnCreateJsonByDynamic_Click(object sender, EventArgs e)
{
dynamic product = new JObject();
product.ProductName = "Elbow Grease";
product.Enabled = true;
product.Price = 4.90m;
product.StockCount = ;
product.StockValue = ;
product.Tags = new JArray("Real", "OnSale");
this.txtJson.Text = product.ToString(); } /// <summary>
/// 从JTokenWriter创建Json
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnJTokenWriter_Click(object sender, EventArgs e)
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartObject();
writer.WritePropertyName("name1");
writer.WriteValue("value1");
writer.WritePropertyName("name2");
writer.WriteStartArray();
writer.WriteValue();
writer.WriteValue();
writer.WriteEndArray();
writer.WriteEndObject(); JObject o = (JObject)writer.Token; this.txtJson.Text = o.ToString();
} /// <summary>
/// 从对象创建Json
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCreateJsonFromObject_Click(object sender, EventArgs e)
{
JValue i = (JValue)JToken.FromObject(); Console.WriteLine(i.Type);
// Integer
Console.WriteLine(i.ToString());
// JValue s = (JValue)JToken.FromObject("A string"); Console.WriteLine(s.Type);
// String
Console.WriteLine(s.ToString());
// A string Computer computer = new Computer
{
Cpu = "Intel",
Memory = ,
Drives = new List<string>
{
"DVD",
"SSD"
}
}; JObject o = (JObject)JToken.FromObject(computer); Console.WriteLine(o.ToString());
// {
// "Cpu": "Intel",
// "Memory": 32,
// "Drives": [
// "DVD",
// "SSD"
// ]
// } JArray a = (JArray)JToken.FromObject(computer.Drives); Console.WriteLine(a.ToString());
// [
// "DVD",
// "SSD"
// ]
} /// <summary>
/// 从匿名对象创建
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCreateFromAnaymous_Click(object sender, EventArgs e)
{
List<Post> posts = new List<Post>
{
new Post
{
Title = "Episode VII",
Description = "Episode VII production",
Categories = new List<string>
{
"episode-vii",
"movie"
},
Link = "episode-vii-production.aspx"
}
}; JObject o = JObject.FromObject(new
{
channel = new
{
title = "Star Wars",
link = "http://www.starwars.com",
description = "Star Wars blog.",
item =
from p in posts
orderby p.Title
select new
{
title = p.Title,
description = p.Description,
link = p.Link,
category = p.Categories
}
}
}); this.txtJson.Text=o.ToString(); } /// <summary>
/// Parse
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnJArrayParse_Click(object sender, EventArgs e)
{
string json = @"[
'Small',
'Medium',
'Large'
]"; JArray a = JArray.Parse(json); this.txtJson.Text = a.ToString();
this.txtJson.Text += "\r\n"; json = @"{
CPU: 'Intel',
Drives: [
'DVD read/writer',
'500 gigabyte hard drive'
]
}"; JObject o = JObject.Parse(json); this.txtJson.Text += o.ToString(); JToken t1 = JToken.Parse("{}"); Console.WriteLine(t1.Type);
// Object JToken t2 = JToken.Parse("[]"); Console.WriteLine(t2.Type);
// Array JToken t3 = JToken.Parse("null"); Console.WriteLine(t3.Type);
// Null JToken t4 = JToken.Parse(@"'A string!'"); Console.WriteLine(t4.Type);
// String
} private void btnDeserializeJsonLinq_Click(object sender, EventArgs e)
{
string json = @"[
{
'Title': 'Json.NET is awesome!',
'Author': {
'Name': 'James Newton-King',
'Twitter': '@JamesNK',
'Picture': '/jamesnk.png'
},
'Date': '2013-01-23T19:30:00',
'BodyHtml': '<h3>Title!</h3>\r\n<p>Content!</p>'
}
]"; JArray blogPostArray = JArray.Parse(json); IList<BlogPost> blogPosts = blogPostArray.Select(p => new BlogPost
{
Title = (string)p["Title"],
AuthorName = (string)p["Author"]["Name"],
AuthorTwitter = (string)p["Author"]["Twitter"],
PostedDate = (DateTime)p["Date"],
Body = HttpUtility.HtmlDecode((string)p["BodyHtml"])
}).ToList(); this.txtJson.Text=(blogPosts[].Body); } private void btnSerializeJson_Click(object sender, EventArgs e)
{
IList<BlogPost> blogPosts = new List<BlogPost>
{
new BlogPost
{
Title = "Json.NET is awesome!",
AuthorName = "James Newton-King",
AuthorTwitter = "JamesNK",
PostedDate = new DateTime(, , , , , ),
Body = @"<h3>Title!</h3>
<p>Content!</p>"
}
}; JArray blogPostsArray = new JArray(
blogPosts.Select(p => new JObject
{
{ "Title", p.Title },
{
"Author", new JObject
{
{ "Name", p.AuthorName },
{ "Twitter", p.AuthorTwitter }
}
},
{ "Date", p.PostedDate
},
{ "BodyHtml", HttpUtility.HtmlEncode(p.Body) },
})
); this.txtJson.Text=(blogPostsArray.ToString()); } /// <summary>
/// 修改Json
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnModifyJson_Click(object sender, EventArgs e)
{
string json = @"{
'channel': {
'title': 'Star Wars',
'link': 'http://www.starwars.com',
'description': 'Star Wars blog.',
'obsolete': 'Obsolete value',
'item': []
}
}"; JObject rss = JObject.Parse(json); JObject channel = (JObject)rss["channel"]; channel["title"] = ((string)channel["title"]).ToUpper();
channel["description"] = ((string)channel["description"]).ToUpper(); channel.Property("obsolete").Remove(); channel.Property("description").AddAfterSelf(new JProperty("new", "New value")); JArray item = (JArray)channel["item"];
item.Add("Item 1");
item.Add("Item 2"); this.txtJson.Text=rss.ToString();
} /// <summary>
/// 合并Json
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnMergeJson_Click(object sender, EventArgs e)
{
JObject o1 = JObject.Parse(@"{
'FirstName': 'John',
'LastName': 'Smith',
'Enabled': false,
'Roles': [ 'User' ]
}");
JObject o2 = JObject.Parse(@"{
'Enabled': true,
'Roles': [ 'User', 'Admin' ]
}"); o1.Merge(o2, new JsonMergeSettings
{
// union array values together to avoid duplicates
MergeArrayHandling = MergeArrayHandling.Union
}); this.txtJson.Text = o1.ToString();
} /// <summary>
/// 查询Json
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnQueryJson_Click(object sender, EventArgs e)
{
string json = @"{
'channel': {
'title': 'James Newton-King',
'link': 'http://james.newtonking.com',
'description': 'James Newton-King\'s blog.',
'item': [
{
'title': 'Json.NET 1.3 + New license + Now on CodePlex',
'description': 'Annoucing the release of Json.NET 1.3, the MIT license and the source on CodePlex',
'link': 'http://james.newtonking.com/projects/json-net.aspx',
'category': [
'Json.NET',
'CodePlex'
]
},
{
'title': 'LINQ to JSON beta',
'description': 'Annoucing LINQ to JSON',
'link': 'http://james.newtonking.com/projects/json-net.aspx',
'category': [
'Json.NET',
'LINQ'
]
}
]
}
}"; JObject rss = JObject.Parse(json); string rssTitle = (string)rss["channel"]["title"]; Console.WriteLine(rssTitle);
// James Newton-King string itemTitle = (string)rss["channel"]["item"][]["title"]; Console.WriteLine(itemTitle);
// Json.NET 1.3 + New license + Now on CodePlex JArray categories = (JArray)rss["channel"]["item"][]["category"]; Console.WriteLine(categories);
// [
// "Json.NET",
// "CodePlex"
// ] string[] categoriesText = categories.Select(c => (string)c).ToArray(); Console.WriteLine(string.Join(", ", categoriesText));
// Json.NET, CodePlex
} private void btnQueryWithLinq_Click(object sender, EventArgs e)
{
string json = @"{
'channel': {
'title': 'James Newton-King',
'link': 'http://james.newtonking.com',
'description': 'James Newton-King\'s blog.',
'item': [
{
'title': 'Json.NET 1.3 + New license + Now on CodePlex',
'description': 'Annoucing the release of Json.NET 1.3, the MIT license and the source on CodePlex',
'link': 'http://james.newtonking.com/projects/json-net.aspx',
'category': [
'Json.NET',
'CodePlex'
]
},
{
'title': 'LINQ to JSON beta',
'description': 'Annoucing LINQ to JSON',
'link': 'http://james.newtonking.com/projects/json-net.aspx',
'category': [
'Json.NET',
'LINQ'
]
}
]
}
}"; JObject rss = JObject.Parse(json); var postTitles =
from p in rss["channel"]["item"]
select (string)p["title"]; foreach (var item in postTitles)
{
Console.WriteLine(item);
}
//LINQ to JSON beta
//Json.NET 1.3 + New license + Now on CodePlex var categories =
from c in rss["channel"]["item"].Children()["category"].Values<string>()
group c by c
into g
orderby g.Count() descending
select new { Category = g.Key, Count = g.Count() }; foreach (var c in categories)
{
Console.WriteLine(c.Category + " - Count: " + c.Count);
}
//Json.NET - Count: 2
//LINQ - Count: 1
//CodePlex - Count: 1
} private void btnJsonToXml_Click(object sender, EventArgs e)
{
string json = @"{
'@Id': 1,
'Email': 'james@example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
],
'Team': {
'@Id': 2,
'Name': 'Software Developers',
'Description': 'Creators of fine software products and services.'
}
}"; XNode node = JsonConvert.DeserializeXNode(json, "Root"); this.txtJson.Text=(node.ToString()); } private void btnXmlToJson_Click(object sender, EventArgs e)
{
string xml = @"<?xml version='1.0' standalone='no'?>
<root>
<person id='1'>
<name>Alan</name>
<url>http://www.google.com</url>
</person>
<person id='2'>
<name>Louis</name>
<url>http://www.yahoo.com</url>
</person>
</root>"; XmlDocument doc = new XmlDocument();
doc.LoadXml(xml); string json = JsonConvert.SerializeXmlNode(doc); this.txtJson.Text=json;
}
}
备注:
关于Json的功能有很多,这里只是列举了一些基本的例子,其他的功能需要自己在用到的时候去查阅相关文档了。
关于使用说明文档可以去官网【http://www.newtonsoft.com/json】查看。Samples实例的网址如下:http://www.newtonsoft.com/json/help/html/Samples.htm
--------------------------------------------------------------------------------