繁体   English   中英

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

[英]C# Parse JSON response (Get a specific part from 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"
    }
  ]
}

我正在尝试获取此代码

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

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

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());

我正在使用 C#。

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,
        };
    }
}

反序列化

您会注意到我们还有为我们生成的用于序列化和反序列化的转换器。 反序列化位非常简单:

 var result = JsonConvert.DeserializeObject<GettingStarted>(json);

result变量开始并使用点找到你的项目......

var description = result.results.lexicalEntries.First()
    .entries.First()
    .senses.First()
    .definitions.First();

所有这些First()调用都是由于数据的每个部分都是数组。 您需要为此引用System.Linq 如果您有多个或少于一个,在任何这些级别(您可能需要处理集合或执行更多遍历),您将需要阅读一些内容。

您可以创建一个类,其属性是您尝试解析的 JSON 的名称。 这样您就可以将 JSON 反序列化为该类的一个实例并提取您需要的任何属性。 您需要使用 Newtonsoft.Json 包。

示例类:

public class YourClass
{
    public string propertyA { get; set; }
    public string propertyB { get; set; }
 }

然后在你的主代码中:

YourClass yourClass = new YourClass();
try
{
    yourClass = JsonConvert.DeserializeObject<YourClass>(yourJsonStringGoesHere);
}
catch (Exception ex)
{
        //log exception here
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM