7

我有一个看起来像这样的 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"
          }
     ]
}

它在数组中包含的对象比上面的示例显示的要多得多。无论如何,我需要根据 wvw_match_id 选择 Json 对象。

我将如何实现这一目标?:)

4

2 回答 2

9

由于从评论中您似乎已经对使用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");
        }

    }
}

输出:

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
于 2013-09-20T23:47:32.580 回答
0

You should just serialize it as you normally would then filter the array with LINQ. So I'm just going to assume you've defined a class for the objects in this array, call it MyObj

MyObj[] myObjects = serializer.Deserialize<MyObj[]>(jsonAsAString);
var filteredObjs = myObjects.Where(x => x.wvw_match_id == "the id i'm filtering on");

Keep in mind it's much easier to work with native C# objects than JSON. JSON.NET is for doing the serialization/deserialization. Filtering your collection is something you want to do with iteration or LINQ.

于 2013-09-20T22:28:59.713 回答