Json.NET - Documentation Creating JSON

本文介绍了如何使用LINQ高效地创建JSON对象,包括数组和对象的创建方式,以及如何从集合中创建JSON数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Setting values and creating objects and arrays one at a time gives you total control but it is more verbose than other options.

Creating JSON Copy imageCopy

 1JArray array = new JArray();

 2JValue text = new JValue("Manual text");

 3JValue date = new JValue(new DateTime(2000, 5, 23));

 4

 5array.Add(text);

 6array.Add(date);

 7

 8string json = array.ToString();

 9// [

10//   "Manual text",

11//   "2000-05-23T00:00:00"

12// ]

Creating JSON with LINQ


Declaratively creating JSON objects using LINQ is a fast way to create JSON from collections of values.

Creating JSON Declaratively Copy imageCopy

 1List<Post> posts = GetPosts();

 2

 3JObject rss =

 4    new JObject(

 5        new JProperty("channel",

 6            new JObject(

 7                new JProperty("title", "James Newton-King"),

 8                new JProperty("link", "http://james.newtonking.com"),

 9                new JProperty("description", "James Newton-King's blog."),

10                new JProperty("item",

11                    new JArray(

12                        from p in posts

13                        orderby p.Title

14                        select new JObject(

15                            new JProperty("title", p.Title),

16                            new JProperty("description", p.Description),

17                            new JProperty("link", p.Link),

18                            new JProperty("category",

19                                new JArray(

20                                    from c in p.Categories

21                                    select new JValue(c)))))))));

22

23Console.WriteLine(rss.ToString());

24

25//{

26//  "channel": {

27//    "title": "James Newton-King",

28//    "link": "http://james.newtonking.com",

29//    "description": "James Newton-King's blog.",

30//    "item": [

31//      {

32//        "title": "Json.NET 1.3 + New license + Now on CodePlex",

33//        "description": "Annoucing the release of Json.NET 1.3, the MIT license and being available on CodePlex",

34//        "link": "http://james.newtonking.com/projects/json-net.aspx",

35//   


转载于:https://my.oschina.net/bv10000/blog/299790

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值