如何将Json响应转换为C#对象?

问题描述

我已将Newtonsoft.Json添加到我的项目中。

我正在使用以下代码在https://apiseeds.com/documentation/lyrics处调用歌词API:

LyricClient = new HttpClient
{
    BaseAddress = new Uri("https://orion.apiseeds.com/api/music/lyric")
};
LyricClient.DefaultRequestHeaders.Accept.Clear();
LyricClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

string url = LyricClient.BaseAddress + "/" + artist + "/" + track;

var result = await LyricClient.GetAsync(url + "?apikey=" + ApiSeedsKey);

if (result.IsSuccessStatusCode)
{
    var resultString = await result.Content.ReadAsStringAsync();
}

并获得包含所有已命名字段和适当值(为清楚起见而格式化)的结果字符串:

{
  "result":
  {
    "artist":
    {
      "name": "Marianne Faithfull"
    },"track":
    {
      "name": "Broken English","text": "[Verse 1]...","lang":
      {
        "code": "en","name": "English"
      }
    },"copyright":
    {
      "notice": "Broken English lyrics are property and copyright of their owners. Commercial use is not allowed.","artist": "Copyright Marianne Faithfull","text": "All lyrics provided for educational purposes and personal use only."
    },"probability": 100,"similarity": 1
  }
}

到目前为止,很好。

但是,当我尝试将其转换为C#对象时,我可以在程序中对其进行操作/显示,但我没有得到任何数据。

我已经创建了一个Result对象

public class Result
{
    public Artist Artist { get; set; }
    public Track Track { get; set; }
    public Copyright Copyright { get; set; }
    public double Probability { get; set; }
    public double Similarity { get; set; } 
}

以及具有与Json中的名称相匹配的属性的其他子对象以保存此数据,例如:

public class Artist
{
    public string Name { get; set; }
}

但是,当我打电话

var resultObject = JsonConvert.DeserializeObject<Result>(resultString);

我得到一个Result对象,但是所有属性都设置为null或0。

我尝试使属性名称小写并将[DataContract][DataMember]属性添加到类中,但这对结果没有影响。我已经检查了示例以及诸如此类的地方

https://www.c-sharpcorner.com/article/json-serialization-and-deserialization-in-c-sharp/

https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to

似乎并不矛盾我所做的事情,但我仍然无法使其正常工作。我肯定在类声明中缺少一些明显的东西,但我无法弄清楚。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...