Jaz*_*rix 4 c# json object json.net
我有一个看起来像这样的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"
}
]
}
Run Code Online (Sandbox Code Playgroud)
它包含的数组中的对象比上面显示的示例多得多.无论如何,我需要根据wvw_match_id选择Json对象.
我怎么做到这一点?:)
因为从评论中可以看出你对使用JObject
和Linq 的想法已经半熟了,所以这是一个示例程序,演示如何使用该方法从ID获取JSON的特定匹配:
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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)