Json.NET使用入门(六)【LINQ to JSON】

前端之家收集整理的这篇文章主要介绍了Json.NET使用入门(六)【LINQ to JSON】前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

手动创建JSON

本示例以编程方式一次创建JObject和JArray实例。

JArray array@H_404_7@ = new@H_404_7@ JArray();
            array@H_404_7@.Add("Manual text"@H_404_7@);
            array@H_404_7@.Add(new@H_404_7@ DateTime(2000@H_404_7@,5@H_404_7@,23@H_404_7@));

            JObject o = new@H_404_7@ JObject();
            o["MyArray"@H_404_7@] = array@H_404_7@;

            string@H_404_7@ json = o.ToString();
            // {@H_404_7@
            // "MyArray": [@H_404_7@
            // "Manual text",@H_404_7@
            // "2000-05-23T00:00:00"@H_404_7@
            // ]@H_404_7@
            // }@H_404_7@

使用集合初始化器创建JSON

JObject o = new@H_404_7@ JObject
            {
                 { "cpu"@H_404_7@,"Intel"@H_404_7@ },{ "Memory"@H_404_7@,32@H_404_7@ },{
                   "Drives"@H_404_7@,new@H_404_7@ JArray
                   {
                            "DVD"@H_404_7@,"SSD"@H_404_7@
                    }
                 }
            };
            Console.WriteLine(o.ToString());

            // {@H_404_7@
            // "cpu": "Intel",@H_404_7@
            // "Memory": 32,@H_404_7@
            // "Drives": [@H_404_7@
            // "DVD",@H_404_7@
            // "SSD"@H_404_7@
            // ]@H_404_7@
            // }@H_404_7@

用LINQ声明创建JSON

public@H_404_7@ class@H_404_7@ Post
{
    public@H_404_7@ string@H_404_7@ Title { get@H_404_7@; set@H_404_7@; }
    public@H_404_7@ string@H_404_7@ Description { get@H_404_7@; set@H_404_7@; }
    public@H_404_7@ string@H_404_7@ Link { get@H_404_7@; set@H_404_7@; }
    public@H_404_7@ IList<string@H_404_7@> Categories { get@H_404_7@; set@H_404_7@; }
}
List<Post> posts = GetPosts();

JObject RSS =
    new@H_404_7@ JObject(
        new@H_404_7@ JProperty("channel"@H_404_7@,new@H_404_7@ JObject(
                new@H_404_7@ JProperty("title"@H_404_7@,"James Newton-King"@H_404_7@),new@H_404_7@ JProperty("link"@H_404_7@,"http://james.newtonking.com"@H_404_7@),new@H_404_7@ JProperty("description"@H_404_7@,"James Newton-King's blog."@H_404_7@),new@H_404_7@ JProperty("item"@H_404_7@,new@H_404_7@ JArray(
                        from@H_404_7@ p in@H_404_7@ posts
                        orderby@H_404_7@ p.Title
                        select@H_404_7@ new@H_404_7@ JObject(
                            new@H_404_7@ JProperty("title"@H_404_7@,p.Title),p.Description),p.Link),new@H_404_7@ JProperty("category"@H_404_7@,new@H_404_7@ JArray(
                                    from@H_404_7@ c in@H_404_7@ p.Categories
                                    select@H_404_7@ new@H_404_7@ JValue(c)))))))));

Console.WriteLine(RSS.ToString());

// {@H_404_7@
// "channel": {@H_404_7@
// "title": "James Newton-King",@H_404_7@
// "link": "http://james.newtonking.com",@H_404_7@
// "description": "James Newton-King's blog.",@H_404_7@
// "item": [@H_404_7@
// {@H_404_7@
// "title": "Json.NET 1.3 + New license + Now on CodePlex",@H_404_7@
// "description": "Annoucing the release of Json.NET 1.3,the MIT license and being available on CodePlex",@H_404_7@
// "link": "http://james.newtonking.com/projects/json-net.aspx",@H_404_7@
// "category": [@H_404_7@
// "Json.NET",@H_404_7@
// "CodePlex"@H_404_7@
// ]@H_404_7@
// },@H_404_7@
// {@H_404_7@
// "title": "LINQ to JSON beta",@H_404_7@
// "description": "Annoucing LINQ to JSON",@H_404_7@
// "LINQ"@H_404_7@
// ]@H_404_7@
// }@H_404_7@
// ]@H_404_7@
// }@H_404_7@
// }@H_404_7@

动态创建JSON

本示例使用C#动态功能创建JObject和JArray实例。

dynamic product = new JObject();@H_404_7@
product.ProductName@H_404_7@ = "Elbow Grease"@H_404_7@;@H_404_7@
product.Enabled@H_404_7@ = true;@H_404_7@
product.Price@H_404_7@ = 4.90@H_404_7@m;@H_404_7@
product.StockCount@H_404_7@ = 9000@H_404_7@;@H_404_7@
product.StockValue@H_404_7@ = 44100@H_404_7@;@H_404_7@
product.Tags@H_404_7@ = new JArray("Real"@H_404_7@,"OnSale"@H_404_7@);@H_404_7@

Console.WriteLine@H_404_7@(product.ToString@H_404_7@());@H_404_7@
// {
//   "ProductName"@H_404_7@: "Elbow Grease"@H_404_7@,//   "Enabled"@H_404_7@: true,//   "Price"@H_404_7@: 4.90@H_404_7@,//   "StockCount"@H_404_7@: 9000@H_404_7@,//   "StockValue"@H_404_7@: 44100@H_404_7@,//   "Tags"@H_404_7@: [
//     "Real"@H_404_7@,//     "OnSale"@H_404_7@
//   ]
// }

使用JTokenWriter创建JSON

JTokenWriter writer = new JTokenWriter();@H_404_7@
writer.WriteStartObject@H_404_7@();@H_404_7@
writer.WritePropertyName@H_404_7@("name1"@H_404_7@);@H_404_7@
writer.WriteValue@H_404_7@("value1"@H_404_7@);@H_404_7@
writer.WritePropertyName@H_404_7@("name2"@H_404_7@);@H_404_7@
writer.WriteStartArray@H_404_7@();@H_404_7@
writer.WriteValue@H_404_7@(1@H_404_7@);@H_404_7@
writer.WriteValue@H_404_7@(2@H_404_7@);@H_404_7@
writer.WriteEndArray@H_404_7@();@H_404_7@
writer.WriteEndObject@H_404_7@();@H_404_7@

JObject o = (JObject)writer.Token@H_404_7@;@H_404_7@

Console.WriteLine@H_404_7@(o.ToString@H_404_7@());@H_404_7@
// {
//   "name1"@H_404_7@: "value1"@H_404_7@,//   "name2"@H_404_7@: [
//     1@H_404_7@,//     2@H_404_7@
//   ]
// }

对象创建JSON

这个示例使用JToken.FromObject(Object)将.NET值转换为LINQ to JSON

public@H_404_7@ class@H_404_7@ Computer
{
    public@H_404_7@ string@H_404_7@ cpu { get@H_404_7@; set@H_404_7@; }
    public@H_404_7@ int@H_404_7@ Memory { get@H_404_7@; set@H_404_7@; }
    public@H_404_7@ IList<string@H_404_7@> Drives { get@H_404_7@; set@H_404_7@; }
}
JValue i = (JValue)JToken.FromObject@H_404_7@(12345@H_404_7@);@H_404_7@

Console.WriteLine@H_404_7@(i.Type@H_404_7@);@H_404_7@
// Integer
Console.WriteLine@H_404_7@(i.ToString@H_404_7@());@H_404_7@
// 12345@H_404_7@

JValue s = (JValue)JToken.FromObject@H_404_7@("A string"@H_404_7@);@H_404_7@

Console.WriteLine@H_404_7@(s.Type@H_404_7@);@H_404_7@
// String
Console.WriteLine@H_404_7@(s.ToString@H_404_7@());@H_404_7@
// A string

Computer computer = new Computer
{
    cpu = "Intel"@H_404_7@,Memory = 32@H_404_7@,Drives = new List<string>
    {
        "DVD"@H_404_7@,"SSD"@H_404_7@
    }
};@H_404_7@

JObject o = (JObject)JToken.FromObject@H_404_7@(computer);@H_404_7@

Console.WriteLine@H_404_7@(o.ToString@H_404_7@());@H_404_7@
// {
//   "cpu"@H_404_7@: "Intel"@H_404_7@,//   "Memory"@H_404_7@: 32@H_404_7@,//   "Drives"@H_404_7@: [
//     "DVD"@H_404_7@,//     "SSD"@H_404_7@
//   ]
// }

JArray a = (JArray)JToken.FromObject@H_404_7@(computer.Drives@H_404_7@);@H_404_7@

Console.WriteLine@H_404_7@(a.ToString@H_404_7@());@H_404_7@
// [
//   "DVD"@H_404_7@,//   "SSD"@H_404_7@
// ]

从匿名类型创建JSON

public@H_404_7@ class@H_404_7@ Post
{
    public@H_404_7@ string@H_404_7@ Title { get@H_404_7@; set@H_404_7@; }
    public@H_404_7@ string@H_404_7@ Description { get@H_404_7@; set@H_404_7@; }
    public@H_404_7@ string@H_404_7@ Link { get@H_404_7@; set@H_404_7@; }
    public@H_404_7@ IList<string@H_404_7@> Categories { get@H_404_7@; set@H_404_7@; }
}
List@H_404_7@<@H_404_7@Post>@H_404_7@ posts =@H_404_7@ new@H_404_7@ List@H_404_7@<@H_404_7@Post>@H_404_7@
{
    new@H_404_7@ Post
    {
        Title =@H_404_7@ "Episode VII"@H_404_7@,Description =@H_404_7@ "Episode VII production"@H_404_7@,Categories =@H_404_7@ new@H_404_7@ List@H_404_7@<@H_404_7@string@H_404_7@>@H_404_7@
        {
            "episode-vii"@H_404_7@,"movie"@H_404_7@
        },Link@H_404_7@ =@H_404_7@ "episode-vii-production.aspx"@H_404_7@
    }
};

JObject o =@H_404_7@ JObject.@H_404_7@FromObject(new@H_404_7@
{
    channel =@H_404_7@ new@H_404_7@
    {
        title =@H_404_7@ "Star Wars"@H_404_7@,link@H_404_7@ =@H_404_7@ "http://www.starwars.com"@H_404_7@,description =@H_404_7@ "Star Wars blog."@H_404_7@,item =@H_404_7@
            from p in@H_404_7@ posts
            orderby p.@H_404_7@Title
            select@H_404_7@ new@H_404_7@
            {
                title =@H_404_7@ p.@H_404_7@Title,description =@H_404_7@ p.@H_404_7@Description,link@H_404_7@ =@H_404_7@ p.@H_404_7@Link@H_404_7@,category =@H_404_7@ p.@H_404_7@Categories
            }
    }
});

Console.@H_404_7@WriteLine(o.@H_404_7@ToString());
// {@H_404_7@
// "channel": {@H_404_7@
// "title": "Star Wars",@H_404_7@
// "link": "http://www.starwars.com",@H_404_7@
// "description": "Star Wars blog.",@H_404_7@
// "item": [@H_404_7@
// {@H_404_7@
// "title": "Episode VII",@H_404_7@
// "description": "Episode VII production",@H_404_7@
// "link": "episode-vii-production.aspx",@H_404_7@
// "category": [@H_404_7@
// "episode-vii",@H_404_7@
// "movie"@H_404_7@
// ]@H_404_7@
// }@H_404_7@
// ]@H_404_7@
// }@H_404_7@
// }@H_404_7@

使用JArray.Parse解析JSON数组

string json = @"[ 'Small','Medium','Large' ]"@H_404_7@;

JArray@H_404_7@ a = JArray@H_404_7@.Parse@H_404_7@(json);

Console@H_404_7@.WriteLine@H_404_7@(a.ToString@H_404_7@());
//@H_404_7@ [
//@H_404_7@   "Small"@H_404_7@,//@H_404_7@   "Medium"@H_404_7@,//@H_404_7@   "Large"@H_404_7@
// ]@H_404_7@

使用JObject.Parse解析JSON对象

string@H_404_7@ json = @"{ cpu: 'Intel',Drives: [ 'DVD read/writer','500 gigabyte hard drive' ] }"@H_404_7@;

JObject o = JObject.Parse(json);

Console.WriteLine(o.ToString());
// {@H_404_7@
// "cpu": "Intel",@H_404_7@
// "Drives": [@H_404_7@
// "DVD read/writer",@H_404_7@
// "500 gigabyte hard drive"@H_404_7@
// ]@H_404_7@
// }@H_404_7@

使用JToken.Parse解析所有的JSON

JToken t1 = JToken.Parse@H_404_7@("{}"@H_404_7@);@H_404_7@

Console.WriteLine@H_404_7@(t1.Type@H_404_7@);@H_404_7@
// Object

JToken t2 = JToken.Parse@H_404_7@("[]"@H_404_7@);@H_404_7@

Console.WriteLine@H_404_7@(t2.Type@H_404_7@);@H_404_7@
// Array

JToken t3 = JToken.Parse@H_404_7@("null"@H_404_7@);@H_404_7@

Console.WriteLine@H_404_7@(t3.Type@H_404_7@);@H_404_7@
// Null

JToken t4 = JToken.Parse@H_404_7@(@"'A string!'"@H_404_7@);@H_404_7@

Console.WriteLine@H_404_7@(t4.Type@H_404_7@);@H_404_7@
// String

使用LINQ从JSON反序列化

public@H_404_7@ class@H_404_7@ BlogPost
{
    public@H_404_7@ string@H_404_7@ Title { get@H_404_7@; set@H_404_7@; }
    public@H_404_7@ string@H_404_7@ AuthorName { get@H_404_7@; set@H_404_7@; }
    public@H_404_7@ string@H_404_7@ AuthorTwitter { get@H_404_7@; set@H_404_7@; }
    public@H_404_7@ string@H_404_7@ Body { get@H_404_7@; set@H_404_7@; }
    public@H_404_7@ DateTime PostedDate { get@H_404_7@; set@H_404_7@; }
}
string json = @"@H_404_7@[
  {
    'Title'@H_404_7@: 'Json.NET is awesome!'@H_404_7@,'Author'@H_404_7@: {
      'Name'@H_404_7@: 'James Newton-King'@H_404_7@,'Twitter'@H_404_7@: '@JamesNK'@H_404_7@,'Picture'@H_404_7@: '/jamesnk.png'@H_404_7@
    },'Date'@H_404_7@: '2013-01-23T19:30:00'@H_404_7@,'BodyHtml'@H_404_7@: '&lt;h3&gt;Title!&lt;/h3&gt;\r\n&lt;p&gt;Content!&lt;/p&gt;'@H_404_7@
  }
]"; JArray blogPostArray = JArray.Parse(json); IList<BlogPost> blogPosts = blogPostArray.Select(p => new BlogPost { Title = (string)p["@H_404_7@Title"],AuthorName = (string)p["@H_404_7@Author"]["@H_404_7@Name"],AuthorTwitter = (string)p["@H_404_7@Author"]["@H_404_7@Twitter"],PostedDate = (DateTime)p["@H_404_7@Date"],Body = HttpUtility.HtmlDecode((string)p["@H_404_7@BodyHtml"]) }).ToList(); Console.WriteLine(blogPosts[0].Body); // <h3>Title!</h3> // <p>Content!</p>@H_404_7@

使用LINQ序列化为JSON

本示例使用LINQ to JSON手动将.NET类型转换为JSON

public@H_404_7@ class@H_404_7@ BlogPost
{
    public@H_404_7@ string@H_404_7@ Title { get@H_404_7@; set@H_404_7@; }
    public@H_404_7@ string@H_404_7@ AuthorName { get@H_404_7@; set@H_404_7@; }
    public@H_404_7@ string@H_404_7@ AuthorTwitter { get@H_404_7@; set@H_404_7@; }
    public@H_404_7@ string@H_404_7@ Body { get@H_404_7@; set@H_404_7@; }
    public@H_404_7@ DateTime PostedDate { get@H_404_7@; set@H_404_7@; }
}
IList<BlogPost> blogPosts = new@H_404_7@ List@H_404_7@<BlogPost>
{
    new@H_404_7@ BlogPost
    {
        Title = "Json.NET is awesome!"@H_404_7@,AuthorName = "James Newton-King"@H_404_7@,AuthorTwitter = "JamesNK"@H_404_7@,PostedDate = new@H_404_7@ DateTime(2013@H_404_7@,1@H_404_7@,23@H_404_7@,19@H_404_7@,30@H_404_7@,0@H_404_7@),Body = @"<h3>Title!</h3> <p>Content!</p>"@H_404_7@
    }
};

JArray blogPostsArray = new@H_404_7@ JArray(
    blogPosts.Select(p => new@H_404_7@ JObject
    {
        { "Title"@H_404_7@,p.Title },{
            "Author"@H_404_7@,new@H_404_7@ JObject
            {
                { "Name"@H_404_7@,p.AuthorName },{ "Twitter"@H_404_7@,p.AuthorTwitter }
            }
        },{ "Date"@H_404_7@,p.PostedDate },{ "BodyHtml"@H_404_7@,HttpUtility.HtmlEncode(p.Body) },})
    );

Console.WriteLine(blogPostsArray.ToString());
// [@H_404_7@
// {@H_404_7@
// "Title": "Json.NET is awesome!",@H_404_7@
// "Author": {@H_404_7@
// "Name": "James Newton-King",@H_404_7@
// "Twitter": "JamesNK"@H_404_7@
// },@H_404_7@
// "Date": "2013-01-23T19:30:00",@H_404_7@
// "BodyHtml": "&lt;h3&gt;Title!&lt;/h3&gt;\r\n&lt;p&gt;Content!&lt;/p&gt;"@H_404_7@
// }@H_404_7@
// ]@H_404_7@

修改JSON

此示例加载JSON,修改JObject和JArray实例,然后再次写出JSON

string json = @"{ '@H_404_7@channel'@H_404_7@: {
    'title'@H_404_7@: 'Star Wars'@H_404_7@,'link'@H_404_7@: 'http://www.starwars.com'@H_404_7@,'description'@H_404_7@: 'Star Wars blog.'@H_404_7@,'obsolete'@H_404_7@: 'Obsolete value'@H_404_7@,'item'@H_404_7@: []@H_404_7@
  }
}"; JObject RSS = JObject.Parse(json); JObject channel = (JObject)RSS["@H_404_7@channel"]; channel["@H_404_7@title"] = ((string)channel["@H_404_7@title"]).ToUpper(); channel["@H_404_7@description"] = ((string)channel["@H_404_7@description"]).ToUpper(); channel.Property("@H_404_7@obsolete").Remove(); channel.Property("@H_404_7@description").AddAfterSelf(new JProperty("@H_404_7@new","@H_404_7@New value")); JArray item = (JArray)channel["@H_404_7@item"]; item.Add("@H_404_7@Item 1@H_404_7@"); item.Add("@H_404_7@Item 2@H_404_7@"); Console.WriteLine(RSS.ToString()); // { // "@H_404_7@channel": { // "@H_404_7@title": "@H_404_7@STAR WARS",// "@H_404_7@link": "@H_404_7@http://www.starwars.com",@H_404_7@
// "description": "STAR WARS BLOG.",@H_404_7@
// "new": "New value",@H_404_7@
// "item": [@H_404_7@
// "Item 1",@H_404_7@
// "Item 2"@H_404_7@
// ]@H_404_7@
// }@H_404_7@
// }@H_404_7@

合并JSON

此示例将LINQ to JSON对象合并

JObject o1 = JObject.@H_404_7@Parse(@"{ '@H_404_7@FirstName'@H_404_7@: 'John'@H_404_7@,'LastName'@H_404_7@: 'Smith'@H_404_7@,'Enabled'@H_404_7@: false,'Roles'@H_404_7@: [ 'User'@H_404_7@ ]@H_404_7@
}"); JObject o2 = JObject.Parse(@"@H_404_7@{
  'Enabled'@H_404_7@: true,'Roles'@H_404_7@: [ 'User'@H_404_7@,'Admin'@H_404_7@ ]@H_404_7@
}"); o1.Merge(o2,new JsonMergeSettings { // union array values together to avoid duplicates MergeArrayHandling = MergeArrayHandling.Union }); string json = o1.ToString(); // { // "@H_404_7@FirstName": "@H_404_7@John",// "@H_404_7@LastName": "@H_404_7@Smith",// "@H_404_7@Enabled": true,// "@H_404_7@Roles": [ // "@H_404_7@User",// "@H_404_7@Admin" // ] // }@H_404_7@

查询JSON

此示例加载JSON,然后使用Item[Object] 索引器从其中查询值,然后将返回的标记转换为.NET值

string json = @"@H_404_7@{
  'channel'@H_404_7@: {
    'title'@H_404_7@: 'James Newton-King'@H_404_7@,'link'@H_404_7@: 'http://james.newtonking.com'@H_404_7@,'description'@H_404_7@: 'James Newton-King\'s blog.'@H_404_7@,'item'@H_404_7@: [
      {
        'title'@H_404_7@: 'Json.NET 1.3 + New license + Now on CodePlex'@H_404_7@,'description'@H_404_7@: 'Annoucing the release of Json.NET 1.3,the MIT license and the source on CodePlex'@H_404_7@,'link'@H_404_7@: 'http://james.newtonking.com/projects/json-net.aspx'@H_404_7@,'category'@H_404_7@: [
          'Json.NET'@H_404_7@,'CodePlex'@H_404_7@
        ]
      },{
        'title'@H_404_7@: 'LINQ to JSON beta'@H_404_7@,'description'@H_404_7@: 'Annoucing LINQ to JSON'@H_404_7@,'LINQ'@H_404_7@
        ]
      }
    ]
  }
}"; JObject RSS = JObject.Parse(json); string RSSTitle = (string)RSS["@H_404_7@channel"]["@H_404_7@title"]; Console.WriteLine(RSSTitle); // James Newton-King string itemTitle = (string)RSS["@H_404_7@channel"]["@H_404_7@item"][0]["@H_404_7@title"]; Console.WriteLine(itemTitle); // Json.NET 1.3 + New license + Now on CodePlex JArray categories = (JArray)RSS["@H_404_7@channel"]["@H_404_7@item"][0]["@H_404_7@category"]; Console.WriteLine(categories); // [ // "@H_404_7@Json.NET",// "@H_404_7@CodePlex" // ] string[] categoriesText = categories.Select(c => (string)c).ToArray(); Console.WriteLine(string.Join("@H_404_7@,",categoriesText)); // Json.NET,CodePlex@H_404_7@

用动态查询JSON

此示例加载JSON,然后使用C#动态功能从中查询

string json = @"@H_404_7@[
  {
    'Title'@H_404_7@: 'Json.NET is awesome!'@H_404_7@,'BodyHtml'@H_404_7@: '&lt;h3&gt;Title!&lt;/h3&gt;\r\n&lt;p&gt;Content!&lt;/p&gt;'@H_404_7@
  }
]"; dynamic blogPosts = JArray.Parse(json); dynamic blogPost = blogPosts[0]; string title = blogPost.Title; Console.WriteLine(title); // Json.NET is awesome! string author = blogPost.Author.Name; Console.WriteLine(author); // James Newton-King DateTime postDate = blogPost.Date; Console.WriteLine(postDate); // 23/01/2013 7:30:00 p.m.@H_404_7@

用LINQ查询JSON

string@H_404_7@ 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','LINQ' ] } ] } }"@H_404_7@;

JObject RSS = JObject.Parse(json);

var@H_404_7@ postTitles =
    from@H_404_7@ p in@H_404_7@ RSS["channel"@H_404_7@]["item"@H_404_7@]
    select@H_404_7@ (string@H_404_7@)p["title"@H_404_7@];

foreach@H_404_7@ (var@H_404_7@ item in@H_404_7@ postTitles)
{
    Console.WriteLine(item);
}
//LINQ to JSON beta@H_404_7@
//Json.NET 1.3 + New license + Now on CodePlex@H_404_7@

var@H_404_7@ categories =
    from@H_404_7@ c in@H_404_7@ RSS["channel"@H_404_7@]["item"@H_404_7@].Children()["category"@H_404_7@].Values<string@H_404_7@>()
    group@H_404_7@ c by c
    into@H_404_7@ g
    orderby@H_404_7@ g.Count() descending@H_404_7@
    select@H_404_7@ new@H_404_7@ { Category = g.Key,Count = g.Count() };

foreach@H_404_7@ (var@H_404_7@ c in@H_404_7@ categories)
{
    Console.WriteLine(c.Category + " - Count: "@H_404_7@ + c.Count);
}
//Json.NET - Count: 2@H_404_7@
//LINQ - Count: 1@H_404_7@
//CodePlex - Count: 1@H_404_7@

用SelectToken查询JSON

此示例加载JSON,然后使用 SelectToken(String)从它查询值。

JObject o = JObject.Parse(@"@H_404_7@{
  'Stores'@H_404_7@: [
    'Lambton Quay'@H_404_7@,'Willis Street'@H_404_7@
  ],'Manufacturers'@H_404_7@: [
    {
      'Name'@H_404_7@: 'Acme Co'@H_404_7@,'Products'@H_404_7@: [
        {
          'Name'@H_404_7@: 'Anvil'@H_404_7@,'Price'@H_404_7@: 50@H_404_7@
        }
      ]
    },{
      'Name'@H_404_7@: 'Contoso'@H_404_7@,'Products'@H_404_7@: [
        {
          'Name'@H_404_7@: 'Elbow Grease'@H_404_7@,'Price'@H_404_7@: 99.95@H_404_7@
        },{
          'Name'@H_404_7@: 'Headlight Fluid'@H_404_7@,'Price'@H_404_7@: 4@H_404_7@
        }
      ]
    }
  ]
}"); string name = (string)o.SelectToken("@H_404_7@Manufacturers[0@H_404_7@].Name"); Console.WriteLine(name); // Acme Co decimal productPrice = (decimal)o.SelectToken("@H_404_7@Manufacturers[0@H_404_7@].Products[0@H_404_7@].Price"); Console.WriteLine(productPrice); // 50 string productName = (string)o.SelectToken("@H_404_7@Manufacturers[1@H_404_7@].Products[0@H_404_7@].Name"); Console.WriteLine(productName); // Elbow Grease@H_404_7@

用SelectToken查询JSON并转义属性

此示例加载JSON时需要使用 SelectToken(String)查询时需要转义的属性

JObject o = JObject.Parse(@"{ 'Space Invaders': 'Taito','Doom ]|[': 'id',""Yar's Revenge"": 'Atari','Government ""Intelligence""': 'Make-Believe' }"@H_404_7@);

string@H_404_7@ spaceInvaders = (string@H_404_7@)o.SelectToken("['Space Invaders']"@H_404_7@);
// Taito@H_404_7@

string@H_404_7@ doom3 = (string@H_404_7@)o.SelectToken("['Doom ]|[']"@H_404_7@);
// id@H_404_7@

string@H_404_7@ yarsRevenge = (string@H_404_7@)o.SelectToken("['Yar\\'s Revenge']"@H_404_7@);
// Atari@H_404_7@

string@H_404_7@ governmentIntelligence = (string@H_404_7@)o.SelectToken("['Government \"Intelligence\"']"@H_404_7@);
// Make-Believe@H_404_7@

用SelectToken和LINQ查询JSON

此示例加载JSON,然后使用SelectToken(String)和LINQ运算符的组合来从中查询值。

JObject o = JObject.Parse(@"@H_404_7@{
  'Stores'@H_404_7@: [
    'Lambton Quay'@H_404_7@,'Price'@H_404_7@: 4@H_404_7@
        }
      ]
    }
  ]
}"); string[] storeNames = o.SelectToken("@H_404_7@Stores").Select(s => (string)s).ToArray(); Console.WriteLine(string.Join("@H_404_7@,storeNames)); // Lambton Quay,Willis Street string[] firstProductNames = o["@H_404_7@Manufacturers"].Select(m => (string)m.SelectToken("@H_404_7@Products[1@H_404_7@].Name")) .Where(n => n != null).ToArray(); Console.WriteLine(string.Join("@H_404_7@,firstProductNames)); // Headlight Fluid decimal totalPrice = o["@H_404_7@Manufacturers"].Sum(m => (decimal)m.SelectToken("@H_404_7@Products[0@H_404_7@].Price")); Console.WriteLine(totalPrice); // 149.95@H_404_7@

用JSONPath查询JSON

此示例加载JSON,然后使用带有JSONPath查询SelectToken(String)从其中查询值。

JObject o = JObject.Parse(@"@H_404_7@{
  'Stores'@H_404_7@: [
    'Lambton Quay'@H_404_7@,'Price'@H_404_7@: 4@H_404_7@
        }
      ]
    }
  ]
}"); // manufacturer with the name 'Acme Co' JToken acme = o.SelectToken("@H_404_7@$.@H_404_7@Manufacturers[?(@.@H_404_7@Name == 'Acme Co'@H_404_7@)]"); Console.WriteLine(acme); // { "@H_404_7@Name": "@H_404_7@Acme Co",Products: [{ "@H_404_7@Name": "@H_404_7@Anvil","@H_404_7@Price": 50 }] } // name of all products priced 50 and above IEnumerable<JToken> pricyProducts = o.SelectTokens("@H_404_7@$.@H_404_7@.Products[?(@.@H_404_7@Price >= 50@H_404_7@)].Name"); foreach (JToken item in pricyProducts) { Console.WriteLine(item); } // Anvil // Elbow Grease@H_404_7@

文件中读取JSON

JObject o1 = JObject.Parse(File.ReadAllText(@"c:\videogames.json"@H_404_7@));

// read JSON directly from a file@H_404_7@
using@H_404_7@ (StreamReader file = File.OpenText(@"c:\videogames.json"@H_404_7@))
using@H_404_7@ (JsonTextReader reader = new@H_404_7@ JsonTextReader(file))
{
    JObject o2 = (JObject)JToken.ReadFrom(reader);
}

将JSON写入一个文件

JObject videogameRatings = new@H_404_7@ JObject(
    new@H_404_7@ JProperty("Halo"@H_404_7@,9@H_404_7@),new@H_404_7@ JProperty("Starcraft"@H_404_7@,new@H_404_7@ JProperty("Call of Duty"@H_404_7@,7.5@H_404_7@));

File.WriteAllText(@"c:\videogames.json"@H_404_7@,videogameRatings.ToString());

// write JSON directly to a file@H_404_7@
using@H_404_7@ (StreamWriter file = File.CreateText(@"c:\videogames.json"@H_404_7@))
using@H_404_7@ (JsonTextWriter writer = new@H_404_7@ JsonTextWriter(file))
{
    videogameRatings.WriteTo(writer);
}

将JSON转换为集合

此示例使用ToObject<T>()将LINQ to JSON对象转换为.NET类型

string json = @"@H_404_7@{
  'd'@H_404_7@: [
    {
      'Name'@H_404_7@: 'John Smith'@H_404_7@
    },{
      'Name'@H_404_7@: 'Mike Smith'@H_404_7@
    }
  ]
}"; JObject o = JObject.Parse(json); JArray a = (JArray)o["@H_404_7@d"]; IList<Person> person = a.ToObject<IList<Person>>(); Console.WriteLine(person[0].Name); // John Smith Console.WriteLine(person[1].Name); // Mike Smith@H_404_7@
@H_301_1581@将JSON转换为值

此示例使用ToObject<T>()将LINQ to JSON对象转换为.NET类型

JValue v1 = new@H_404_7@ JValue(true@H_404_7@);

bool@H_404_7@ b = v1.ToObject<bool@H_404_7@>();

Console.WriteLine(b);
// true@H_404_7@

int@H_404_7@ i = v1.ToObject<int@H_404_7@>();

Console.WriteLine(i);
// 1@H_404_7@

string@H_404_7@ s = v1.ToObject<string@H_404_7@>();

Console.WriteLine(s);
// "True"@H_404_7@

将JSON转换为类型

此示例使用 ToObject(Type)将LINQ to JSON对象转换为.NET类型

JValue v1 = new@H_404_7@ JValue(true@H_404_7@);

bool@H_404_7@ b = (bool@H_404_7@)v1.ToObject(typeof@H_404_7@(bool@H_404_7@));

Console.WriteLine(b);
// true@H_404_7@

int@H_404_7@ i = (int@H_404_7@)v1.ToObject(typeof@H_404_7@(int@H_404_7@));

Console.WriteLine(i);
// 1@H_404_7@

string@H_404_7@ s = (string@H_404_7@)v1.ToObject(typeof@H_404_7@(string@H_404_7@));

Console.WriteLine(s);
// "True"@H_404_7@

转换JValue

此示例将JValue实例转换为.NET值

JValue v1 = new@H_404_7@ JValue("1"@H_404_7@);
int@H_404_7@ i = (int@H_404_7@)v1;

Console.WriteLine(i);
// 1@H_404_7@

JValue v2 = new@H_404_7@ JValue(true@H_404_7@);
bool@H_404_7@ b = (bool@H_404_7@)v2;

Console.WriteLine(b);
// true@H_404_7@

JValue v3 = new@H_404_7@ JValue("19.95"@H_404_7@);
decimal@H_404_7@ d = (decimal@H_404_7@)v3;

Console.WriteLine(d);
// 19.95@H_404_7@

JValue v4 = new@H_404_7@ JValue(new@H_404_7@ DateTime(2013@H_404_7@,21@H_404_7@));
string@H_404_7@ s = (string@H_404_7@)v4;

Console.WriteLine(s);
// 01/21/2013 00:00:00@H_404_7@

JValue v5 = new@H_404_7@ JValue("http://www.bing.com"@H_404_7@);
Uri u = (Uri)v5;

Console.WriteLine(u);
// http://www.bing.com/@H_404_7@

JValue v6 = JValue.CreateNull();
u = (Uri)v6;

Console.WriteLine((u != null@H_404_7@) ? u.ToString() : "{null}"@H_404_7@);
// {null}@H_404_7@

DateTime? dt = (DateTime?)v6;

Console.WriteLine((dt != null@H_404_7@) ? dt.ToString() : "{null}"@H_404_7@);
// {null}@H_404_7@

使用JValue.Value

JValue s = new JValue("A string value"@H_404_7@);@H_404_7@

Console.WriteLine@H_404_7@(s.Value@H_404_7@.GetType@H_404_7@().Name@H_404_7@);@H_404_7@
// String
Console.WriteLine@H_404_7@(s.Value@H_404_7@);@H_404_7@
// A string value

JValue u = new JValue(new Uri("http://www.google.com/"@H_404_7@));@H_404_7@

Console.WriteLine@H_404_7@(u.Value@H_404_7@.GetType@H_404_7@().Name@H_404_7@);@H_404_7@
// Uri
Console.WriteLine@H_404_7@(u.Value@H_404_7@);@H_404_7@
// http://www.google@H_404_7@.com@H_404_7@/

使用JObject.Properties

此示例使用Properties()获取对象的JProperty集合

JObject o = new@H_404_7@ JObject
{
    { "name1"@H_404_7@,"value1"@H_404_7@ },{ "name2"@H_404_7@,"value2"@H_404_7@ }
};

foreach@H_404_7@ (JProperty property in@H_404_7@ o.Properties())
{
    Console.WriteLine(property.Name + " - "@H_404_7@ + property.Value);
}
// name1 - value1@H_404_7@
// name2 - value2@H_404_7@

foreach@H_404_7@ (KeyValuePair<string@H_404_7@,JToken> property in@H_404_7@ o)
{
    Console.WriteLine(property.Key + " - "@H_404_7@ + property.Value);
}
// name1 - value1@H_404_7@
// name2 - value2@H_404_7@

使用LINQ to JSON注解

本示例使用LINQ to JSON对象的注释

JObject o = JObject.Parse(@"{ 'name': 'Bill G','age': 58,'country': 'United States','employer': 'Microsoft' }"@H_404_7@);

o.AddAnnotation(new@H_404_7@ HashSet<string@H_404_7@>());
o.PropertyChanged += (sender,args) => o.Annotation<HashSet<string@H_404_7@>>().Add(args.PropertyName);

o["age"@H_404_7@] = 59@H_404_7@;
o["employer"@H_404_7@] = "Bill & Melinda Gates Foundation"@H_404_7@;

HashSet<string@H_404_7@> changedProperties = o.Annotation<HashSet<string@H_404_7@>>();
// age@H_404_7@
// employer@H_404_7@

比较JSON和JToken.DeepEquals

此示例使用DeepEquals(JToken,JToken)比较JToken实例,比较令牌和所有子令牌

JValue s1 = new@H_404_7@ JValue("A string"@H_404_7@);
JValue s2 = new@H_404_7@ JValue("A string"@H_404_7@);
JValue s3 = new@H_404_7@ JValue("A STRING"@H_404_7@);

Console.WriteLine(JToken.DeepEquals(s1,s2));
// true@H_404_7@

Console.WriteLine(JToken.DeepEquals(s2,s3));
// false@H_404_7@

JObject o1 = new@H_404_7@ JObject
{
    { "Integer"@H_404_7@,12345@H_404_7@ },{ "String"@H_404_7@,"A string"@H_404_7@ },{ "Items"@H_404_7@,new@H_404_7@ JArray(1@H_404_7@,2@H_404_7@) }
};

JObject o2 = new@H_404_7@ JObject
{
    { "Integer"@H_404_7@,2@H_404_7@) }
};

Console.WriteLine(JToken.DeepEquals(o1,o2));
// true@H_404_7@

Console.WriteLine(JToken.DeepEquals(s1,o1["String"@H_404_7@]));
// true@H_404_7@

使用JToken.DeepClone克隆JSON

此示例使用 DeepClone()递归地克隆一个JToken及其所有子项

JObject o1 = new@H_404_7@ JObject
{
    { "String"@H_404_7@,"A string!"@H_404_7@ },2@H_404_7@) }
};

Console.WriteLine(o1.ToString());
// {@H_404_7@
// "String": "A string!",@H_404_7@
// "Items": [@H_404_7@
// 1,@H_404_7@
// 2@H_404_7@
// ]@H_404_7@
// }@H_404_7@

JObject o2 = (JObject)o1.DeepClone();

Console.WriteLine(o2.ToString());
// {@H_404_7@
// "String": "A string!",@H_404_7@
// 2@H_404_7@
// ]@H_404_7@
// }@H_404_7@

Console.WriteLine(JToken.DeepEquals(o1,o2));
// true@H_404_7@

Console.WriteLine(Object@H_404_7@.ReferenceEquals(o1,o2));
// false@H_404_7@

用JToken.ToString写JSON文本

本示例将LINQ to JSON对象转换为JSON

JObject o = JObject.Parse@H_404_7@(@"{'string1':'value','integer2':99,'datetime3':'2000-05-23T00:00:00'}"@H_404_7@);@H_404_7@

Console.WriteLine@H_404_7@(o.ToString@H_404_7@());@H_404_7@
// {
//   "string1"@H_404_7@: "value"@H_404_7@,//   "integer2"@H_404_7@: 99@H_404_7@,//   "datetime3"@H_404_7@: "2000-05-23T00:00:00"@H_404_7@
// }

Console.WriteLine@H_404_7@(o.ToString@H_404_7@(Formatting.None@H_404_7@));@H_404_7@
// {"string1"@H_404_7@:"value"@H_404_7@,"integer2"@H_404_7@:99@H_404_7@,"datetime3"@H_404_7@:"2000-05-23T00:00:00"@H_404_7@}

Console.WriteLine@H_404_7@(o.ToString@H_404_7@(Formatting.None@H_404_7@,new JavaScriptDateTimeConverter()));@H_404_7@
// {"string1"@H_404_7@:"value"@H_404_7@,"datetime3"@H_404_7@:new Date(959032800000@H_404_7@)}

与JsonConverter一起使用JToken.ToString

本示例使用JsonConverter自定义将LINQ to JSON对象转换为JSON

JObject o = JObject.Parse(@"@H_404_7@{'string1'@H_404_7@:'value'@H_404_7@,'integer2'@H_404_7@:99@H_404_7@,'datetime3'@H_404_7@:'2000-05-23T00:00:00'@H_404_7@}"); Console.WriteLine(o.ToString(Formatting.None,new JavaScriptDateTimeConverter())); // {"@H_404_7@string1":"@H_404_7@value","@H_404_7@integer2":99,"@H_404_7@datetime3":new Date(959032800000)}@H_404_7@

使用JToken.CreateReader

本示例从JToken创建一个JTokenReader

JObject o = new@H_404_7@ JObject
{
    { "cpu"@H_404_7@,{
        "Drives"@H_404_7@,new@H_404_7@ JArray
        {
            "DVD"@H_404_7@,"SSD"@H_404_7@
        }
    }
};

JsonReader reader = o.CreateReader();
while@H_404_7@ (reader.Read())
{
    Console.Write(reader.TokenType);
    if@H_404_7@ (reader.Value != null@H_404_7@)
    {
        Console.Write(" - "@H_404_7@ + reader.Value);
    }

    Console.WriteLine();
}

// StartObject@H_404_7@
// PropertyName - cpu@H_404_7@
// String - Intel@H_404_7@
// PropertyName - Memory@H_404_7@
// Integer - 32@H_404_7@
// PropertyName - Drives@H_404_7@
// StartArray@H_404_7@
// String - DVD@H_404_7@
// String - SSD@H_404_7@
// EndArray@H_404_7@
// EndObject@H_404_7@

使用JToken.CreateWriter

本示例从JToken创建一个JTokenWriter

JObject o = new JObject
{
    { "name1"@H_404_7@,"value2"@H_404_7@ }
};@H_404_7@

JsonWriter writer = o.CreateWriter@H_404_7@();@H_404_7@
writer.WritePropertyName@H_404_7@("name3"@H_404_7@);@H_404_7@
writer.WriteStartArray@H_404_7@();@H_404_7@
writer.WriteValue@H_404_7@(1@H_404_7@);@H_404_7@
writer.WriteValue@H_404_7@(2@H_404_7@);@H_404_7@
writer.WriteEndArray@H_404_7@();@H_404_7@

Console.WriteLine@H_404_7@(o.ToString@H_404_7@());@H_404_7@
// {
//   "name1"@H_404_7@: "value1"@H_404_7@,//   "name2"@H_404_7@: "value2"@H_404_7@,//   "name3"@H_404_7@: [
//     1@H_404_7@,//     2@H_404_7@
//   ]
// }

从BSON读取

本示例使用BsonReader从BSON读取JObject

byte@H_404_7@[] data = Convert.FromBase64String("KQAAAAJuYW1lMQAHAAAAdmFsdWUxAAJuYW1lMgAHAAAAdmFsdWUyAAA="@H_404_7@);
MemoryStream ms = new@H_404_7@ MemoryStream(data);

JObject o;
using@H_404_7@ (BsonReader reader = new@H_404_7@ BsonReader(ms))
{
    o = (JObject)JToken.ReadFrom(reader);
}

string@H_404_7@ value@H_404_7@ = (string@H_404_7@)o["name1"@H_404_7@];

Console.WriteLine(value@H_404_7@);
// value1@H_404_7@

写为BSON

本示例使用BsonWriter将JObject写入BSON

JObject o =@H_404_7@ new@H_404_7@ JObject
{
    { "name1"@H_404_7@,"value2"@H_404_7@ }
};

MemoryStream ms =@H_404_7@ new@H_404_7@ MemoryStream();
using (BsonWriter writer =@H_404_7@ new@H_404_7@ BsonWriter(ms))
{
    o.@H_404_7@WriteTo(writer);
}

string@H_404_7@ data@H_404_7@ =@H_404_7@ Convert.@H_404_7@ToBase64String(ms.@H_404_7@ToArray());

Console.@H_404_7@WriteLine(data@H_404_7@);
// KQAAAAJuYW1lMQAHAAAAdmFsdWUxAAJuYW1lMgAHAAAAdmFsdWUyAAA=@H_404_7@

猜你在找的Json相关文章