在 Windows 窗体中使用 C# 从 JSON 中提取文本

发布于 2025-01-11 02:40:30 字数 4014 浏览 0 评论 0原文

我正在使用 OXFO​​RD DICTIONARY API,它赋予单词意义。它以 JSON 格式返回结果,因此我只想从 JSON 中提取单词的含义。我正在使用 C# NEWTONSOFT 包,但无法获得输出。非常感谢我在任何帮助下面附加的代码和输出屏幕截图。

using System;
using Newtonsoft.Json;
using System.IO;
using System.Text.Json;
public class Program
{
    public static void Main()
    {
        string word_id = " ";
        Console.WriteLine("Enter a word : ");
        word_id= Console.ReadLine();
        const string lang_code = "en-gb";
        const string fields = "definitions";
        const string strictMatch = "false";
        string WEBSERVICE_URL = "https://od-api.oxforddictionaries.com:443/api/v2/entries/" + lang_code + '/' + word_id + "?fields=" + fields + "&strictMatch=" + strictMatch;
        try
        {
#pragma warning disable SYSLIB0014 // Type or member is obsolete
            var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
#pragma warning restore SYSLIB0014 // Type or member is obsolete
            if (webRequest != null)
            {
                webRequest.Method = "GET";
                webRequest.Timeout = 12000;
                webRequest.ContentType = "application/json";
                webRequest.Headers.Add("app_id", "xxxxxxx");
                webRequest.Headers.Add("app_key", "xxxxxxxxxxxxxxxxxxxxxxxxxx");

                using System.IO.Stream s = webRequest.GetResponse().GetResponseStream();
                using System.IO.StreamReader sr = new System.IO.StreamReader(s);
                var jsonresponse = sr.ReadToEnd();
                var jdata = JsonConvert.DeserializeObject<details>(jsonresponse);
                Console.WriteLine("Meaning : ", arg0: jdata.results.lexicalEntries.entries.senses.definitions);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

        
    }
}

public class details
{
    public string id { get; set; }
    public Metadata metadata { get; set; }
    public results results { get; set; }
    public string word { get; set; }

}

public class Metadata
{
    public string? operation{ get; set; }
    public string? provider { get; set; }
    public string? schema{ get; set; }
}

public class results
{
    public string? id { get; set; }
    public string? language { get; set; }
    public lexicalEntries lexicalEntries { get; set; }
    public string? type { get; set; }
    public string? word { get; set; }
}

public class lexicalEntries
{
    public entries entries { get; set; }
}

public class entries
{
    public senses senses { get; set; }
}

public class senses
{
    public string definitions { get; set; }
    public string id { get; set; }
}


上述代码的输出

JSON 输出:

{
    "id": "necrosis",
    "metadata": {
        "operation": "retrieve",
        "provider": "Oxford University Press",
        "schema": "RetrieveEntry"
    },
    "results": [
        {
            "id": "necrosis",
            "language": "en-gb",
            "lexicalEntries": [
                {
                    "entries": [
                        {
                            "senses": [
                                {
                                    "definitions": [
                                        "the death of most or all of the cells in an organ or tissue due to disease, injury, or failure of the blood supply."
                                    ],
                                    "id": "m_en_gbus0682990.005"
                                }
                            ]
                        }
                    ],
                    "language": "en-gb",
                    "lexicalCategory": {
                        "id": "noun",
                        "text": "Noun"
                    },
                    "text": "necrosis"
                }
            ],
            "type": "headword",
            "word": "necrosis"
        }
    ],
    "word": "necrosis"
}

I am working with OXFORD DICTIONARY API which gives meaning to a word. It returns the result in JSON format and hence I want to extract only the meaning of the word from the JSON. I am using the C# NEWTONSOFT package but am unable to get the output. The code and output screenshot I attached below any help is highly appreciated.

using System;
using Newtonsoft.Json;
using System.IO;
using System.Text.Json;
public class Program
{
    public static void Main()
    {
        string word_id = " ";
        Console.WriteLine("Enter a word : ");
        word_id= Console.ReadLine();
        const string lang_code = "en-gb";
        const string fields = "definitions";
        const string strictMatch = "false";
        string WEBSERVICE_URL = "https://od-api.oxforddictionaries.com:443/api/v2/entries/" + lang_code + '/' + word_id + "?fields=" + fields + "&strictMatch=" + strictMatch;
        try
        {
#pragma warning disable SYSLIB0014 // Type or member is obsolete
            var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
#pragma warning restore SYSLIB0014 // Type or member is obsolete
            if (webRequest != null)
            {
                webRequest.Method = "GET";
                webRequest.Timeout = 12000;
                webRequest.ContentType = "application/json";
                webRequest.Headers.Add("app_id", "xxxxxxx");
                webRequest.Headers.Add("app_key", "xxxxxxxxxxxxxxxxxxxxxxxxxx");

                using System.IO.Stream s = webRequest.GetResponse().GetResponseStream();
                using System.IO.StreamReader sr = new System.IO.StreamReader(s);
                var jsonresponse = sr.ReadToEnd();
                var jdata = JsonConvert.DeserializeObject<details>(jsonresponse);
                Console.WriteLine("Meaning : ", arg0: jdata.results.lexicalEntries.entries.senses.definitions);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

        
    }
}

public class details
{
    public string id { get; set; }
    public Metadata metadata { get; set; }
    public results results { get; set; }
    public string word { get; set; }

}

public class Metadata
{
    public string? operation{ get; set; }
    public string? provider { get; set; }
    public string? schema{ get; set; }
}

public class results
{
    public string? id { get; set; }
    public string? language { get; set; }
    public lexicalEntries lexicalEntries { get; set; }
    public string? type { get; set; }
    public string? word { get; set; }
}

public class lexicalEntries
{
    public entries entries { get; set; }
}

public class entries
{
    public senses senses { get; set; }
}

public class senses
{
    public string definitions { get; set; }
    public string id { get; set; }
}


Output for above code

JSON OUTPUT:

{
    "id": "necrosis",
    "metadata": {
        "operation": "retrieve",
        "provider": "Oxford University Press",
        "schema": "RetrieveEntry"
    },
    "results": [
        {
            "id": "necrosis",
            "language": "en-gb",
            "lexicalEntries": [
                {
                    "entries": [
                        {
                            "senses": [
                                {
                                    "definitions": [
                                        "the death of most or all of the cells in an organ or tissue due to disease, injury, or failure of the blood supply."
                                    ],
                                    "id": "m_en_gbus0682990.005"
                                }
                            ]
                        }
                    ],
                    "language": "en-gb",
                    "lexicalCategory": {
                        "id": "noun",
                        "text": "Noun"
                    },
                    "text": "necrosis"
                }
            ],
            "type": "headword",
            "word": "necrosis"
        }
    ],
    "word": "necrosis"
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

人疚 2025-01-18 02:40:30

您的主要问题是在尝试从 json 反序列化数组时没有使用数组或列表。

在您更熟悉 JSON 反序列化之前,我特别建议使用 json2csharp.com 或类似的东西来为您生成类。您也可以仅使用它作为起点,但是您获取 json 结果,将其粘贴进去,并且有使它工作所需的所有类。我通常重命名它生成的 Root 类,并在下面将其命名为“Details”。

每当您看到带有这样的方括号的 "property": [ ] 时,这意味着它是一个包含内部内容的数组,因此 C# 中相应的属性必须定义为数组或列表。

  public class Metadata
{
    public string operation { get; set; }
    public string provider { get; set; }
    public string schema { get; set; }
}

public class Senses
{
    public List<string> definitions { get; set; }
    public string id { get; set; }
}

public class Entry
{
    public List<Senses> senses { get; set; }
}

public class LexicalCategory
{
    public string id { get; set; }
    public string text { get; set; }
}

public class LexicalEntry
{
    public List<Entry> entries { get; set; }
    public string language { get; set; }
    public LexicalCategory lexicalCategory { get; set; }
    public string text { get; set; }
}

public class Result
{
    public string id { get; set; }
    public string language { get; set; }
    public List<LexicalEntry> lexicalEntries { get; set; }
    public string type { get; set; }
    public string word { get; set; }
}

public class Details
{
    public string id { get; set; }
    public Metadata metadata { get; set; }
    public List<Result> results { get; set; }
    public string word { get; set; }
}

Your main issue is not using an array or List when trying to deserialize an array from the json.

Until you're more familiar with JSON deserialization, I especially recommend using json2csharp.com or something similar to generate classes for you. You can also just use it as a starting point, but you take your json result, paste it in, and there's all the classes you need to make it work. I generally rename the Root class it generates and have named it Details below.

Whenever you see "property": [ ] with the brackets like that, it means it's an array of whatever is inside, so your corresponding property in C# has to be defined as an array or List.

  public class Metadata
{
    public string operation { get; set; }
    public string provider { get; set; }
    public string schema { get; set; }
}

public class Senses
{
    public List<string> definitions { get; set; }
    public string id { get; set; }
}

public class Entry
{
    public List<Senses> senses { get; set; }
}

public class LexicalCategory
{
    public string id { get; set; }
    public string text { get; set; }
}

public class LexicalEntry
{
    public List<Entry> entries { get; set; }
    public string language { get; set; }
    public LexicalCategory lexicalCategory { get; set; }
    public string text { get; set; }
}

public class Result
{
    public string id { get; set; }
    public string language { get; set; }
    public List<LexicalEntry> lexicalEntries { get; set; }
    public string type { get; set; }
    public string word { get; set; }
}

public class Details
{
    public string id { get; set; }
    public Metadata metadata { get; set; }
    public List<Result> results { get; set; }
    public string word { get; set; }
}
故事↓在人 2025-01-18 02:40:30

您尝试反序列化的类存在一些问题。
您需要创建以下属性数组:

 public class details
    {
    public results[] results { get; set; }
    }

   public class results
    {
        public lexicalEntries[] lexicalEntries { get; set; }
    }
    public class entries
    {
        public senses[] senses { get; set; }
    }
    public class senses
    {
       public string[] definitions { get; set; }
    }
    public class lexicalEntries
   {
     public entries[] entries { get; set; }
   }

我在更新类后设法反序列化您的 JSON 对象。
输入图片此处描述

The classes you are trying to deserialize to has a few problems.
You need to make the following properties arrays:

 public class details
    {
    public results[] results { get; set; }
    }

   public class results
    {
        public lexicalEntries[] lexicalEntries { get; set; }
    }
    public class entries
    {
        public senses[] senses { get; set; }
    }
    public class senses
    {
       public string[] definitions { get; set; }
    }
    public class lexicalEntries
   {
     public entries[] entries { get; set; }
   }

I managed to deserialize your JSON object after updating the classes.
enter image description here

櫻之舞 2025-01-18 02:40:30

我更喜欢使用动态,ExpandoObject 可以帮助你很多

using System.Dynamic;
dynamic ? obj = JsonConvert.DeserializeObject<ExpandoObject>(yourJSON);

obj 具有与 JSON 相同的确切属性,同时它不需要从任何 JSON 创建模型

I prefer using dynamic and ExpandoObject can help you a lot

using System.Dynamic;
dynamic ? obj = JsonConvert.DeserializeObject<ExpandoObject>(yourJSON);

the obj has exact properties as same as your JSON at the same time it does not need to create a model from any JSON

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文