【问题标题】:How do I access the "text" and "audio" objects inside of a deserialized json?如何访问反序列化 json 中的“文本”和“音频”对象?
【发布时间】:2022-01-03 21:43:00
【问题描述】:

我有这段代码,它从this api 下载一个字符串,然后反序列化它。 我已经想出了如何访问“单词”和“语音”对象,但是我将如何访问“语音”数组中的“音频”对象,或者“含义”中的一些对象? 1

        private void Button1_Click(object sender, EventArgs e)
    {
        string result = "";
        string link = ($"https://api.dictionaryapi.dev/api/v2/entries/en/hello");
        var json = new WebClient().DownloadString(link);
        var jsonDes = JsonConvert.DeserializeObject<List<DictionaryAPIResultData>>(json);
        foreach (var data in jsonDes)
        {
            Console.WriteLine( data.phonetics);
        }
    }

    public class DictionaryAPIResultData
    {
        [JsonProperty("word")]
        internal string word { get; set; }
        [JsonProperty("phonetics")]
        internal List<string> phonetics { get; set; }

    }

希望有人能提供帮助!

【问题讨论】:

  • 我建议你使用像 NAUDIO 这样的 n mp3 流媒体,我不认为 c# 声音播放器读取 mp3,只有 wav
  • 顺便说一句,如果你有 JSON 并且你不知道如何围绕它设计你的容器类,那么有一些有用的工具可以为你做这件事。例如:json2csharp.com

标签: c# json winforms


【解决方案1】:

JSON 对象如下所示:

"phonetics":[{"text":"həˈləʊ","audio":"//ssl.gstatic.com/dictionary/static/sounds/20200429/hello--_gb_1.mp3"},{"text":"hɛˈləʊ"}]

所以只需添加另一个类来表示它并将你的反序列化类更改为

 public class DictionaryAPIResultData
{
    [JsonProperty("word")]
    internal string word { get; set; }
    [JsonProperty("phonetics")]
    internal List<Phonetics> phonetics { get; set; }

}
public class Phonetics
{
    public string text { get; set; }
    public string audio { get; set; }
}

仅当您的类属性与 json 中的属性具有不同的名称时,或者您将其从小写更改为大写时,您才需要 JsonProperty 属性

我第一次看错了,所以如果你想播放声音How to play .mp3 file from online resources in C#?,这就是答案...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    • 2019-04-27
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多