1、通过属性名或集合索引获取值
将一个值从LINQ转换为JSON的最简单方法是在JObject
/JArray
上使用Item[Object]
索引,然后将返回的JValue
转换为您想要的类型。
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': 'Announcing the release of Json.NET 1.3, the MIT license and the source on CodePlex', 'link': 'http://james.newtonking.com/projects/json-net.aspx', 'categories': [ 'Json.NET', 'CodePlex' ] }, { 'title': 'LINQ to JSON beta', 'description': 'Announcing LINQ to JSON', 'link': 'http://james.newtonking.com/projects/json-net.aspx', 'categories': [ 'Json.NET', 'LINQ' ] } ] } }"; JObject rss = JObject.Parse(json); string rssTitle = (string)rss["channel"]["title"]; // James Newton-King string itemTitle = (string)rss["channel"]["item"][0]["title"]; // Json.NET 1.3 + New license + Now on CodePlex JArray categories = (JArray)rss["channel"]["item"][0]["categories"]; // ["Json.NET", "CodePlex"] IList<string> categoriesText = categories.Select(c => (string)c).ToList(); // Json.NET // CodePlex
2、用LINQ查询
还可以使用LINQ查询JObject
/JArray
。Children()
以IEnumerable<JToken>
的形式返回JObject
/JArray
的子值,然后可以使用Where
/OrderBy
/Select
LINQ操作符查询这些子值。
Note:
Children()
返回令牌的所有子元素。如果是JObject
,它将返回要处理的属性集合;如果是JArray
,则会得到数组值的集合。
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"].SelectMany(i => i["categories"]).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
LINQ to JSON还可用于手动将JSON转换为.NET对象
public class Shortie
{
public string Original { get; set; }
public string Shortened { get; set; }
public string Short { get; set; }
public ShortieException Error { get; set; }
}
public class ShortieException
{
public int Code { get; set; }
public string ErrorMessage { get; set; }
}
当您处理与.NET对象不匹配的JSON时,在.NET对象之间手动序列化和反序列化非常有用
string jsonText = @"{ 'short': { 'original': 'http://www.foo.com/', 'short': 'krehqk', 'error': { 'code': 0, 'msg': 'No action taken' } } }"; JObject json = JObject.Parse(jsonText); Shortie shortie = new Shortie { Original = (string)json["short"]["original"], Short = (string)json["short"]["short"], Error = new ShortieException { Code = (int)json["short"]["error"]["code"], ErrorMessage = (string)json["short"]["error"]["msg"] } }; Console.WriteLine(shortie.Original); // http://www.foo.com/ Console.WriteLine(shortie.Error.ErrorMessage); // No action taken
相关文档:.NET(C#) Json.Net(newtonsoft)操作处理(解析)JSON数据(LINQ to JSON)