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

宓季同
2023-12-01

手动创建JSON

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

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

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

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

使用集合初始化器创建JSON

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

            // {
            //   "Cpu": "Intel",
            //   "Memory": 32,
            //   "Drives": [
            //     "DVD",
            //     "SSD"
            //   ]
            // }

用LINQ声明创建JSON

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

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

Console.WriteLine(rss.ToString());

// {
//   "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 being available 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"
//         ]
//       }
//     ]
//   }
// }

动态创建JSON

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

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

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

使用JTokenWriter创建JSON

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

JObject o = (JObject)writer.Token;

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

从对象创建JSON

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

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

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

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 = 32,
    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"
// ]

从匿名类型创建JSON

public class Post
{
    public string Title { get; set; }
    public string Description { get; set; }
    public string Link { get; set; }
    public IList<string> Categories { get; set; }
}
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
            }
    }
});

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

使用JArray.Parse解析JSON数组

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

JArray a = JArray.Parse(json);

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

使用JObject.Parse解析JSON对象

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

JObject o = JObject.Parse(json);

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

使用JToken.Parse解析所有的JSON

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

使用LINQ从JSON反序列化

public class BlogPost
{
    public string Title { get; set; }
    public string AuthorName { get; set; }
    public string AuthorTwitter { get; set; }
    public string Body { get; set; }
    public DateTime PostedDate { get; set; }
}
string json = @"[
  {
    'Title': 'Json.NET is awesome!',
    'Author': {
      'Name': 'James Newton-King',
      'Twitter': '@JamesNK',
      'Picture': '/jamesnk.png'
    },
    'Date': '2013-01-23T19:30:00',
    'BodyHtml': '&lt;h3&gt;Title!&lt;/h3&gt;\r\n&lt;p&gt;Content!&lt;/p&gt;'
  }
]";

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

Console.WriteLine(blogPosts[0].Body);
// <h3>Title!</h3>
// <p>Content!</p>

使用LINQ序列化为JSON

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

public class BlogPost
{
    public string Title { get; set; }
    public string AuthorName { get; set; }
    public string AuthorTwitter { get; set; }
    public string Body { get; set; }
    public DateTime PostedDate { get; set; }
}
IList<BlogPost> blogPosts = new List<BlogPost>
{
    new BlogPost
    {
        Title = "Json.NET is awesome!",
        AuthorName = "James Newton-King",
        AuthorTwitter = "JamesNK",
        PostedDate = new DateTime(2013, 1, 23, 19, 30, 0),
        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) },
    })
    );

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

修改JSON

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

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

Console.WriteLine(rss.ToString());
// {
//   "channel": {
//     "title": "STAR WARS",
//     "link": "http://www.starwars.com",
//     "description": "STAR WARS BLOG.",
//     "new": "New value",
//     "item": [
//       "Item 1",
//       "Item 2"
//     ]
//   }
// }

合并JSON

此示例将LINQ to JSON对象合并

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

string json = o1.ToString();
// {
//   "FirstName": "John",
//   "LastName": "Smith",
//   "Enabled": true,
//   "Roles": [
//     "User",
//     "Admin"
//   ]
// }

查询JSON

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

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"][0]["title"];

Console.WriteLine(itemTitle);
// Json.NET 1.3 + New license + Now on CodePlex

JArray categories = (JArray)rss["channel"]["item"][0]["category"];

Console.WriteLine(categories);
// [
//   "Json.NET",
//   "CodePlex"
// ]

string[] categoriesText = categories.Select(c => (string)c).ToArray();

Console.WriteLine(string.Join(", ", categoriesText));
// Json.NET, CodePlex

用动态查询JSON

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

string json = @"[
  {
    'Title': 'Json.NET is awesome!',
    'Author': {
      'Name': 'James Newton-King',
      'Twitter': '@JamesNK',
      'Picture': '/jamesnk.png'
    },
    'Date': '2013-01-23T19:30:00',
    'BodyHtml': '&lt;h3&gt;Title!&lt;/h3&gt;\r\n&lt;p&gt;Content!&lt;/p&gt;'
  }
]";

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.

用LINQ查询JSON

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

用SelectToken查询JSON

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

JObject o = JObject.Parse(@"{
  'Stores': [
    'Lambton Quay',
    'Willis Street'
  ],
  'Manufacturers': [
    {
      'Name': 'Acme Co',
      'Products': [
        {
          'Name': 'Anvil',
          'Price': 50
        }
      ]
    },
    {
      'Name': 'Contoso',
      'Products': [
        {
          'Name': 'Elbow Grease',
          'Price': 99.95
        },
        {
          'Name': 'Headlight Fluid',
          'Price': 4
        }
      ]
    }
  ]
}");

string name = (string)o.SelectToken("Manufacturers[0].Name");

Console.WriteLine(name);
// Acme Co

decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price");

Console.WriteLine(productPrice);
// 50

string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name");

Console.WriteLine(productName);
// Elbow Grease

用SelectToken查询JSON并转义属性

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

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

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

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

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

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

用SelectToken和LINQ查询JSON

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

JObject o = JObject.Parse(@"{
  'Stores': [
    'Lambton Quay',
    'Willis Street'
  ],
  'Manufacturers': [
    {
      'Name': 'Acme Co',
      'Products': [
        {
          'Name': 'Anvil',
          'Price': 50
        }
      ]
    },
    {
      'Name': 'Contoso',
      'Products': [
        {
          'Name': 'Elbow Grease',
          'Price': 99.95
        },
        {
          'Name': 'Headlight Fluid',
          'Price': 4
        }
      ]
    }
  ]
}");

string[] storeNames = o.SelectToken("Stores").Select(s => (string)s).ToArray();

Console.WriteLine(string.Join(", ", storeNames));
// Lambton Quay, Willis Street

string[] firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name"))
    .Where(n => n != null).ToArray();

Console.WriteLine(string.Join(", ", firstProductNames));
// Headlight Fluid

decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price"));

Console.WriteLine(totalPrice);
// 149.95

用JSONPath查询JSON

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

JObject o = JObject.Parse(@"{
  'Stores': [
    'Lambton Quay',
    'Willis Street'
  ],
  'Manufacturers': [
    {
      'Name': 'Acme Co',
      'Products': [
        {
          'Name': 'Anvil',
          'Price': 50
        }
      ]
    },
    {
      'Name': 'Contoso',
      'Products': [
        {
          'Name': 'Elbow Grease',
          'Price': 99.95
        },
        {
          'Name': 'Headlight Fluid',
          'Price': 4
        }
      ]
    }
  ]
}");

// manufacturer with the name 'Acme Co'
JToken acme = o.SelectToken("$.Manufacturers[?(@.Name == 'Acme Co')]");

Console.WriteLine(acme);
// { "Name": "Acme Co", Products: [{ "Name": "Anvil", "Price": 50 }] }

// name of all products priced 50 and above
IEnumerable<JToken> pricyProducts = o.SelectTokens("$..Products[?(@.Price >= 50)].Name");

foreach (JToken item in pricyProducts)
{
    Console.WriteLine(item);
}
// Anvil
// Elbow Grease

从文件中读取JSON

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

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

将JSON写入一个文件

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

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

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

将JSON转换为集合

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

string json = @"{
  'd': [
    {
      'Name': 'John Smith'
    },
    {
      'Name': 'Mike Smith'
    }
  ]
}";

JObject o = JObject.Parse(json);

JArray a = (JArray)o["d"];

IList<Person> person = a.ToObject<IList<Person>>();

Console.WriteLine(person[0].Name);
// John Smith

Console.WriteLine(person[1].Name);
// Mike Smith

将JSON转换为值

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

JValue v1 = new JValue(true);

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

Console.WriteLine(b);
// true

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

Console.WriteLine(i);
// 1

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

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

将JSON转换为类型

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

JValue v1 = new JValue(true);

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

Console.WriteLine(b);
// true

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

Console.WriteLine(i);
// 1

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

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

转换JValue

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

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

Console.WriteLine(i);
// 1

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

Console.WriteLine(b);
// true

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

Console.WriteLine(d);
// 19.95

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

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

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

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

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

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

DateTime? dt = (DateTime?)v6;

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

使用JValue.Value

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

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

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

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

使用JObject.Properties

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

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

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

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

使用LINQ to JSON注解

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

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

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

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

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

比较JSON和JToken.DeepEquals

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

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

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

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

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

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

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

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

使用JToken.DeepClone克隆JSON

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

JObject o1 = new JObject
{
    { "String", "A string!" },
    { "Items", new JArray(1, 2) }
};

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

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

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

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

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

用JToken.ToString写JSON文本

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

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

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

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

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

与JsonConverter一起使用JToken.ToString

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

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

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

使用JToken.CreateReader

本示例从JToken创建一个JTokenReader

JObject o = new JObject
{
    { "Cpu", "Intel" },
    { "Memory", 32 },
    {
        "Drives", new JArray
        {
            "DVD",
            "SSD"
        }
    }
};

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

    Console.WriteLine();
}

// StartObject
// PropertyName - Cpu
// String - Intel
// PropertyName - Memory
// Integer - 32
// PropertyName - Drives
// StartArray
// String - DVD
// String - SSD
// EndArray
// EndObject

使用JToken.CreateWriter

本示例从JToken创建一个JTokenWriter

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

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

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

从BSON读取

本示例使用BsonReader从BSON读取JObject

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

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

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

Console.WriteLine(value);
// value1

写为BSON

本示例使用BsonWriter将JObject写入BSON

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

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

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

Console.WriteLine(data);
// KQAAAAJuYW1lMQAHAAAAdmFsdWUxAAJuYW1lMgAHAAAAdmFsdWUyAAA=
 类似资料: