C#解析JSON响应(从响应中获取特定部分)

-2 c# api parsing json response

我正在尝试从JSON响应字符串中获取特定部分。

这是JSON代码:

{
  "metadata": {
    "provider": "Oxford University Press"
  },
  "results": [
    {
      "id": "door",
      "language": "en",
      "lexicalEntries": [
        {
          "entries": [
            {
              "homographNumber": "000",
              "senses": [
                {
                  "definitions": [
                    "a hinged, sliding, or revolving barrier at the entrance to a building, room, or vehicle, or in the framework of a cupboard"
                  ],
                  "id": "m_en_gbus0290920.005",
                  "subsenses": [
                    {
                      "definitions": [
                        "a doorway"
                      ],
                      "id": "m_en_gbus0290920.008"
                    },
                    {
                      "definitions": [
                        "used to refer to the distance from one building in a row to another"
                      ],
                      "id": "m_en_gbus0290920.009"
                    }
                  ]
                }
              ]
            }
          ],
          "language": "en",
          "lexicalCategory": "Noun",
          "text": "door"
        }
      ],
      "type": "headword",
      "word": "door"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试获取此代码

“定义”:[“在建筑物,房间或车辆的入口处,或在橱柜框架中的铰接,滑动或旋转的屏障”

在一个字符串中这是我的代码:

string language = "en";
            string word_id = textBox1.Text.ToLower();

            String url = "https://od-api.oxforddictionaries.com:443/api/v1/entries/" + language + "/" + word_id+"/definitions";

            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri(url);
            client.DefaultRequestHeaders.Add("app_id", app_Id);
            client.DefaultRequestHeaders.Add("app_key", app_Key);

            HttpResponseMessage response = client.GetAsync(url).Result;
            if (response.IsSuccessStatusCode)
            {
                var result = response.Content.ReadAsStringAsync().Result;
                var s = JsonConvert.DeserializeObject(result);

                textBox2.Text = s.ToString();

            }
            else MessageBox.Show(response.ToString());
Run Code Online (Sandbox Code Playgroud)

我正在使用C#。

Fen*_*ton 5

C#类

第一步是创建一些类,以允许我们用C#表示数据。如果您没有它们,... QuickType可以做到

namespace QuickType
{
    using System;
    using System.Net;
    using System.Collections.Generic;

    using Newtonsoft.Json;

    public partial class GettingStarted
    {
        [JsonProperty("metadata")]
        public Metadata Metadata { get; set; }

        [JsonProperty("results")]
        public Result[] Results { get; set; }
    }

    public partial class Result
    {
        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("language")]
        public string Language { get; set; }

        [JsonProperty("lexicalEntries")]
        public LexicalEntry[] LexicalEntries { get; set; }

        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("word")]
        public string Word { get; set; }
    }

    public partial class LexicalEntry
    {
        [JsonProperty("entries")]
        public Entry[] Entries { get; set; }

        [JsonProperty("language")]
        public string Language { get; set; }

        [JsonProperty("lexicalCategory")]
        public string LexicalCategory { get; set; }

        [JsonProperty("text")]
        public string Text { get; set; }
    }

    public partial class Entry
    {
        [JsonProperty("homographNumber")]
        public string HomographNumber { get; set; }

        [JsonProperty("senses")]
        public Sense[] Senses { get; set; }
    }

    public partial class Sense
    {
        [JsonProperty("definitions")]
        public string[] Definitions { get; set; }

        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("subsenses")]
        public Subsense[] Subsenses { get; set; }
    }

    public partial class Subsense
    {
        [JsonProperty("definitions")]
        public string[] Definitions { get; set; }

        [JsonProperty("id")]
        public string Id { get; set; }
    }

    public partial class Metadata
    {
        [JsonProperty("provider")]
        public string Provider { get; set; }
    }

    public partial class GettingStarted
    {
        public static GettingStarted FromJson(string json) => JsonConvert.DeserializeObject<GettingStarted>(json, Converter.Settings);
    }

    public static class Serialize
    {
        public static string ToJson(this GettingStarted self) => JsonConvert.SerializeObject(self, Converter.Settings);
    }

    public class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

反序列化

您会注意到,我们还有转换器,可以为我们生成序列化和反序列化。反序列化位很简单:

 var result = JsonConvert.DeserializeObject<GettingStarted>(json);
Run Code Online (Sandbox Code Playgroud)

使用

result变量开始,并使用点找到通往项目的路...

var description = result.results.lexicalEntries.First()
    .entries.First()
    .senses.First()
    .definitions.First();
Run Code Online (Sandbox Code Playgroud)

所有这些First()调用是由于数据的每个这些部分都是数组。您需要对此进行参考System.Linq。如果您在以上任何一个级别上拥有一个以上或少于一个,您将需要阅读一些相关的操作(您可能需要使用集合或进行更多遍历)。