简体   繁体   中英

C# Parse JSON response (Get a specific part from response)

I am trying to get a specific part from a JSON response string.

Here is the JSON code :

{
  "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"
    }
  ]
}

I am trying to get this code

"definitions": [ "a hinged, sliding, or revolving barrier at the entrance to a building, room, or vehicle, or in the framework of a cupboard"

in a string Here is my code:

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

I am using C#.

C# Classes

Step one is to create some classes to allow us to represent the data in C#. If you don't have them... QuickType does that .

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

Deserialize

You'll notice that we also have converters to serialize and deserialize generated for us. The deserialize bit is as simple as:

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

Use

Start from the result variable and use dots to find your way down to your item...

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

All of those First() calls are due to each of these parts of the data being arrays. You'll need to reference System.Linq for that. You will want to read a little around what to do if you have more than one, or less than one, at any of those levels (you may need to work with collections, or perform more traversal).

You can create a class whose properties are the names of the JSON you are trying to parse. That way you can deserialize the JSON into an instance of that class and pull whatever property you need. You'll need to use the Newtonsoft.Json package.

Example class:

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

And then in your main code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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