C#无法反序列化当前JSON对象(Newtonsoft)

问题描述 投票:0回答:1

如何获取此数组作为字符串?不幸的是(我是一个初学者),我只知道如何仅获取数组或仅对象,但不知道如何“混合”

enter image description here

    public class TrackContent
    {
        [JsonProperty("track")] public Album Album { get; set; }
    }

    public class Album
    {
        [JsonProperty("album")] public CoverImage CoverImage { get; set; }
    }

    public class CoverImage
    {
        [JsonProperty("image")] public Number Number { get; set; }
    }

    public class Number
    {
        [JsonProperty("3")] public ImageUrl ImageUrl { get; set; }
    }

    public class ImageUrl
    {
        [JsonProperty("#text")] public string Name { get; set; }
    }

    private static void Main(string[] args)
    {
        const string auth = "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=d25de5d2f67d2e5bd459f09378b50b02&artist=Ariana%20Grande&track=One%20Last%20Time&format=json";

        var httpClient = new HttpClient();
        var jsonInfo = httpClient.GetStringAsync(auth);
        var deserializeJson = JsonConvert.DeserializeObject <TrackContent>(jsonInfo.Result);
        Console.WriteLine(deserializeJson.Album.CoverImage.Number.ImageUrl.Name);
    }
c# arrays json http object
1个回答
0
投票

我建议使用诸如http://json2csharp.com/之类的工具从JSON字符串生成C#类。

这将为您提供所需的类,然后您可以使用Newtonsoft对RootObject进行反序列化。


0
投票
public class Streamable
{
    [JsonProperty("#text")] public string text { get; set; }
    public string fulltrack { get; set; }
}

public class Artist
{
    public string name { get; set; }
    public string mbid { get; set; }
    public string url { get; set; }
}

public class Image
{
    [JsonProperty("#text")] public string text { get; set; }
    public string size { get; set; }
}

public class Attr
{
    public string position { get; set; }
}

public class Album
{
    public string artist { get; set; }
    public string title { get; set; }
    public string mbid { get; set; }
    public string url { get; set; }
    public List<Image> image { get; set; }
    [JsonProperty("@atr")] public Attr attr { get; set; }
}

public class Tag
{
    public string name { get; set; }
    public string url { get; set; }
}

public class Toptags
{
    public List<Tag> tag { get; set; }
}

public class Track
{
    public string name { get; set; }
    public string mbid { get; set; }
    public string url { get; set; }
    public string duration { get; set; }
    public Streamable streamable { get; set; }
    public string listeners { get; set; }
    public string playcount { get; set; }
    public Artist artist { get; set; }
    public Album album { get; set; }
    public Toptags toptags { get; set; }
}

public class RootObject
{
    public Track track { get; set; }
}

然后:

var deserializeJson = JsonConvert.DeserializeObject<RootObject>(jsonInfo.Result);
Console.WriteLine(deserializeJson.Album.image[3].text);
© www.soinside.com 2019 - 2024. All rights reserved.