反序列化此JSON文件时出现错误
{
"checkOut": "10:30",
"stars": 4,
"locationId": 953,
"propertyType": 6,
"checkIn": "15:00",
"trustyou": {
"languageSplit": [
{
"tripTypeSplit": [
{
"type": "family",
"percentage": 85
},
{
"type": "couple",
"percentage": 15
}
],
"name": "de",
"percentage": 100
}
],
"location": [
],
"reviewsCount": 83,
"popularity": 0,
"tripTypeSplit": [
{
"type": "family",
"percentage": 86
},
{
"type": "couple",
"percentage": 14
}
],
"sentimentScoreList": [
{
"categoryId": "14",
"ratio": "Good",
"shortText": "Great location",
"name": "Location",
"subcategories": [
],
"highlights": [
{
"text": "Beautiful location",
"confidence": 100
}
],
"reviewCount": 14,
"score": 100
},
{
"categoryId": "111",
"ratio": "Good",
"shortText": "Rather comfortable",
"name": "Comfort",
"subcategories": [
],
"highlights": [
],
"reviewCount": 5,
"score": 100
},
我有这个JSON的以下类
public class Root
{
[JsonProperty("checkIn")]
public string CheckIn { get; set; }
[JsonProperty("distance")]
public double Distance { get; set; }
[JsonProperty("hidden")]
public bool Hidden { get; set; }
[JsonProperty("trustyou")]
public Trustyou Trustyou { get; set; }
[JsonProperty("amenitiesV2")]
public AmenitiesV2 AmenitiesV2 { get; set; }
[JsonProperty("hasAirbnb")]
public bool HasAirbnb { get; set; }
[JsonProperty("checkOut")]
public string CheckOut { get; set; }
[JsonProperty("popularity")]
public int Popularity { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("cntRooms")]
public int CntRooms { get; set; }
似乎有什么问题?我正在使用
对此进行反序列化 string resp2 = await client.GetStringAsync("");
var hotelDetails = JsonConvert.DeserializeObject<IDictionary<string, HotelsDescriptionAPI.Root>>(resp2, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
foreach (var hoteldesc in hotelDetails)
{
MessageBox.Show(hoteldesc.Value.Id);
}
,确切的错误是
"Error converting value 24545 to type and Error converting value "10:30" to type 'HotelsDescriptionAPI.Root'. Path 'checkOut', line 1, position 19."
我试图获得&#34; Id&#34;的价值,我的代码会出现什么问题?
答案 0 :(得分:3)
您的反序列化代码应为:
var hotelDetails = JsonConvert.DeserializeObject<HotelsDescriptionAPI.Root>(resp2,
new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
});
当对象本身只是string,Root
时,您正尝试将其反序列化为Root
字典。
答案 1 :(得分:0)
这似乎不适用于您的情况,但是请注意,当您确实拥有一个数组即JSON(根级子级是数组项,而不是属性)时,您可能必须更改根对象以子类化兼容类型
例如:
public class RootObject : List<ChildObject>
{
}
public class ChildObject
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
答案 2 :(得分:-1)
对于那些没有帮助,并且没有使用Entity Framework和/或手动编写域类的人 - 确保所有类属性都以相同的字段顺序匹配数据源中的内容。