Json.Net基于值选择对象 [英] Json.Net Select Object based on a value
本文介绍了Json.Net基于值选择对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的Json对象:
I have a Json object that looks like this:
{
wvw_matches: [
{
wvw_match_id: "1-4",
red_world_id: 1011,
blue_world_id: 1003,
green_world_id: 1002,
start_time: "2013-09-14T01:00:00Z",
end_time: "2013-09-21T01:00:00Z"
},
{
wvw_match_id: "1-2",
red_world_id: 1017,
blue_world_id: 1021,
green_world_id: 1009,
start_time: "2013-09-14T01:00:00Z",
end_time: "2013-09-21T01:00:00Z"
}
]
}
它在数组中包含的对象比上面的示例显示的要多.无论如何,我需要基于wvw_match_id选择Json对象.
It contains a lot more objects in the array than the example above shows. Anyway, I need to select the Json object based on the wvw_match_id.
我将如何实现? :)
推荐答案
由于从注释中您似乎已经对使用JObject
和Linq的想法有些不满意,因此以下示例程序演示了如何使用该方法通过ID从您的JSON获取特定匹配项:
Since it seems from the comments that you're already semi-comfortable with the idea of using JObject
and Linq, here is an example program demonstrating how to get a specific match from your JSON by ID using that approach:
class Program
{
static void Main(string[] args)
{
string json = @"
{
wvw_matches: [
{
wvw_match_id: ""1-4"",
red_world_id: 1011,
blue_world_id: 1003,
green_world_id: 1002,
start_time: ""2013-09-14T01:00:00Z"",
end_time: ""2013-09-21T01:00:00Z""
},
{
wvw_match_id: ""1-2"",
red_world_id: 1017,
blue_world_id: 1021,
green_world_id: 1009,
start_time: ""2013-09-14T01:00:00Z"",
end_time: ""2013-09-21T01:00:00Z""
}
]
}";
string matchIdToFind = "1-2";
JObject jo = JObject.Parse(json);
JObject match = jo["wvw_matches"].Values<JObject>()
.Where(m => m["wvw_match_id"].Value<string>() == matchIdToFind)
.FirstOrDefault();
if (match != null)
{
foreach (JProperty prop in match.Properties())
{
Console.WriteLine(prop.Name + ": " + prop.Value);
}
}
else
{
Console.WriteLine("match not found");
}
}
}
输出:
wvw_match_id: 1-2
red_world_id: 1017
blue_world_id: 1021
green_world_id: 1009
start_time: 9/14/2013 1:00:00 AM
end_time: 9/21/2013 1:00:00 AM
这篇关于Json.Net基于值选择对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文