【发布时间】:2021-03-30 19:20:23
【问题描述】:
我需要用这种格式反序列化一些 JSON:
{
"message": {
"header": {
"status_code": 200,
"execute_time": 0.29062294960022,
"available": 10000
},
"body": {
"track_list": [
{
"track": {
"track_id": 45085706,
"track_name": "Love Overdose (Deboa & Hannah Holland Remix)",
"primary_genres": {
"music_genre_list": [
{
"music_genre": {
"music_genre_name": "Dance"
}
}
]
}
}
}
]
}
}
}
我有这些课程是从在线生成器获得的,所以我认为它们没问题。
public class Header
{
public int status_code { get; set; }
public double execute_time { get; set; }
public int available { get; set; }
}
public class MusicGenre
{
public int music_genre_id { get; set; }
public int music_genre_parent_id { get; set; }
public string music_genre_name { get; set; }
public string music_genre_name_extended { get; set; }
public string music_genre_vanity { get; set; }
}
public class MusicGenreList
{
public MusicGenre music_genre { get; set; }
}
public class PrimaryGenres
{
public List<MusicGenreList> music_genre_list { get; set; }
}
public class Track
{
public int track_id { get; set; }
public string track_name { get; set; }
public List<object> track_name_translation_list { get; set; }
public int track_rating { get; set; }
public int commontrack_id { get; set; }
public int instrumental { get; set; }
public int @explicit { get; set; }
public int has_lyrics { get; set; }
public int has_subtitles { get; set; }
public int has_richsync { get; set; }
public int num_favourite { get; set; }
public int album_id { get; set; }
public string album_name { get; set; }
public int artist_id { get; set; }
public string artist_name { get; set; }
public string track_share_url { get; set; }
public string track_edit_url { get; set; }
public int restricted { get; set; }
public DateTime updated_time { get; set; }
public PrimaryGenres primary_genres { get; set; }
}
public class TrackList
{
public Track track { get; set; }
}
public class Body
{
public List<TrackList> TrackList { get; set; }
}
public class Message
{
public Header header { get; set; }
public Body body { get; set; }
}
public class Root
{
public Message message { get; set; }
}
我尝试使用以下代码反序列化 JSON:
using (StreamReader r = new StreamReader(@"c:\users\xxxx\desktop\1.json"))
{
string json = r.ReadToEnd();
var tracks = JsonConvert.DeserializeObject<Track>(json);
}
但我什么也没得到。我是新手;用更简单的 JSON 制作它,但我不知道如何用这段代码来做。我想打印一个只有歌曲名称的列表。 如果有人可以帮助我,我将不胜感激!
【问题讨论】:
-
“什么都没有”? 究竟是什么意思?你收到
null回来了吗?您是否得到了带有所有默认值的Track对象?你有例外吗?就此而言,JSON 是什么样的,您可以发布它的副本吗? -
什么都没有。轨道是空的。我发布了一张带有 json 部分的照片
-
您的反序列化必须从顶级类开始,因此您需要更改为: var message = JsonConvert.DeserializeObject
(json); -
请不要发布某个工具如何解释 JSON 的屏幕截图,发布 实际 json。有一些工具是“有用的”,并以“好”(不)理解的方式解释它们,因此它们实际上不是底层 JSON 内容的一对一表示。
-
鉴于您包含 JSON,请尝试
.DeserializeObject<Root>。
标签: c# json api json.net deserialization