38

サーバーからの Json 応答があります。たとえば、次のようになります。

{"routes" : [
  {
     "bounds" : {
        "northeast" : {
           "lat" : 50.4639653,
           "lng" : 30.6325177
        },
        "southwest" : {
           "lat" : 50.4599625,
           "lng" : 30.6272425
        }
     },
     "copyrights" : "Map data ©2013 Google",
     "legs" : [
        {
           "distance" : {
              "text" : "1.7 km",
              "value" : 1729
           },
           "duration" : {
              "text" : "4 mins",
              "value" : 223
           },

そして、トークン「テキスト」の値を取得したい

      "legs" : [
        {
           "distance" : {
              "text" : "1.7 km",
              "value" : 1729
           },

これは、値が「1.7 km」の文字列です。

質問: NewtonsoftJson lib に次のような組み込み関数はありますか?

public string(or JToken) GetJtokenByName(JObject document, string jtokenName)

または、JObject のすべての JToken と JArray で JToken を名前で検索する再帰メソッドを実装する必要がありますか?

4

3 に答える 3

19

これは、json パスとSelectTokenson のメソッドを使用して非常に簡単JTokenです。この方法は非常に優れており、次のようなワイルド カードをサポートしています。

jObject.SelectTokens("routes[*].legs[*].*.text")

このサンプル コードを確認してください。

private class Program
{
    public static void Main(string[] args)
    {
        string json = GetJson();
        JObject jObject = JObject.Parse(json);

        foreach (JToken token in jObject.SelectTokens("routes[*].legs[*].*.text"))
        {
            Console.WriteLine(token.Path + ": " + token);
        }
    }

    private static string GetJson()
    {
        return @" {
        ""routes"": [
        {
            ""bounds"": {
                ""northeast"": {
                    ""lat"": 50.4639653,
                    ""lng"": 30.6325177
                },
                ""southwest"": {
                    ""lat"": 50.4599625,
                    ""lng"": 30.6272425
                }
            },
            ""legs"": [
                {
                    ""distance"": {
                        ""text"": ""1.7 km"",
                        ""value"": 1729
                    },
                    ""duration"": {
                        ""text"": ""4 mins"",
                        ""value"": 223
                    }
                },
                {
                    ""distance"": {
                        ""text"": ""2.3 km"",
                        ""value"": 2301
                    },
                    ""duration"": {
                        ""text"": ""5 mins"",
                        ""value"": 305
                    }
                }
            ]
        }]}";
    }
}

出力は次のとおりです。

routes[0].legs[0].distance.text: 1.7 km
routes[0].legs[0].duration.text: 4 mins
routes[0].legs[1].distance.text: 2.3 km
routes[0].legs[1].duration.text: 5 mins
于 2015-04-21T20:30:34.473 に答える