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

时间:2017-11-01 19:33:27

标签: c# json api parsing 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#。

2 个答案:

答案 0 :(得分:4)

C#Classes

第一步是创建一些类以允许我们用C#表示数据。如果你没有...... QuickType does that

beforeEach(() => {
    wrapper = shallow(
      <FilterableProductTable 
        products={products}/>
    )
  });

  // Checking the intitial state
  it('should initialize the filterText state to an empty string', () => {
    expect(wrapper).to.have.state('filterText').to.equal('');
  });

反序列化

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

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()。如果您在任何这些级别中有多个或少于一个(您可能需要使用集合或执行更多遍历),您将需要阅读一些有关该怎么做的内容。

答案 1 :(得分:0)

您可以创建一个类,其属性是您要解析的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
}