我正试图使用json.net反序列化从web提取的json字符串,但我收到了一个无法反序列化json对象的错误。这是json字符串
{
"metadata": {
"page": 1,
"perPage": 23,
"count": 23
},
"results": [
{
"id": 9,
"name": "Breaks",
"slug": "breaks",
"subgenres": []
},
{
"id": 10,
"name": "Chill Out",
"slug": "chill-out",
"subgenres": []
},
{
"id": 12,
"name": "Deep House",
"slug": "deep-house",
"subgenres": []
},
{
"id": 16,
"name": "DJ Tools",
"slug": "dj-tools",
"subgenres": []
},
{
"id": 1,
"name": "Drum & Bass",
"slug": "drum-and-bass",
"subgenres": []
},
{
"id": 18,
"name": "Dubstep",
"slug": "dubstep",
"subgenres": []
},
{
"id": 17,
"name": "Electro House",
"slug": "electro-house",
"subgenres": []
},
{
"id": 3,
"name": "Electronica",
"slug": "electronica",
"subgenres": []
},
{
"id": 40,
"name": "Funk / R&B",
"slug": "funk-r-and-b",
"subgenres": []
},
{
"id": 49,
"name": "Glitch Hop",
"slug": "glitch-hop",
"subgenres": []
},
{
"id": 8,
"name": "Hard Dance",
"slug": "hard-dance",
"subgenres": []
},
{
"id": 2,
"name": "Hardcore / Hard Techno",
"slug": "hardcore-hard-techno",
"subgenres": []
},
{
"id": 38,
"name": "Hip-Hop",
"slug": "hip-hop",
"subgenres": []
},
{
"id": 5,
"name": "House",
"slug": "house",
"subgenres": []
},
{
"id": 37,
"name": "Indie Dance / Nu Disco",
"slug": "indie-dance-nu-disco",
"subgenres": []
},
{
"id": 14,
"name": "Minimal",
"slug": "minimal",
"subgenres": []
},
{
"id": 39,
"name": "Pop / Rock",
"slug": "pop-rock",
"subgenres": []
},
{
"id": 15,
"name": "Progressive House",
"slug": "progressive-house",
"subgenres": []
},
{
"id": 13,
"name": "Psy-Trance",
"slug": "psy-trance",
"subgenres": []
},
{
"id": 41,
"name": "Reggae / Dub",
"slug": "reggae-dub",
"subgenres": []
},
{
"id": 11,
"name": "Tech House",
"slug": "tech-house",
"subgenres": []
},
{
"id": 6,
"name": "Techno",
"slug": "techno",
"subgenres": []
},
{
"id": 7,
"name": "Trance",
"slug": "trance",
"subgenres": []
}
]
}
And my classes
public class Genres
{
public Metadata metadata { get; set; }
public List<Result> results { get; set; }
}
public class Metadata
{
public int page {get; set; }
public int perPage { get; set;}
public int count { get; set; }
}
public class Result
{
public int id { get; set; }
public string name { get; set; }
public string slug { get; set; }
public List<object> subgenres { get; set; }
}
以及我使用json.net.反序列化数据的代码
void beatportTest_GetDataCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
List<Result> data = JsonConvert.DeserializeObject<List<Result>>(e.Result);
//foreach loop to display data
我希望能够显示Results类中每个流派的名称,但在我的应用程序编译时出现了错误。
JSON数据有两个主要元素元数据和结果。根据你的类结构,Genres类也有相同的结构。但是在您的代码中,您正试图将结构反序列化为Results,这就是您收到错误的原因
您应该尝试反序列化到Genres类
新代码将类似于
void beatportTest_GetDataCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
Genres data = JsonConvert.DeserializeObject(e.Result);
// for-each loop to display data
}
catch(Exception ex)
{
}
}