我无法在C#中将json反序列化为Dictionary<string, List<Purchas>>
。
这是我的.json
:
{
"Ukraine": {
{
"Credits": 500,
"Name": "Clever goat",
"Price": {
"Amount": 100,
"Currency": "UAH"
}
},
{
"Credits": 1000,
"Name": "Smart hare",
"Price": {
"Amount": 190,
"Currency": "UAH"
}
}
},
"USA": {
{
"Credits": 500,
"Name": "Clever goat",
"Price": {
"Amount": 10,
"Currency": "USD"
}
},
{
"Credits": 1000,
"Name": "Smart hare",
"Price": {
"Amount": 19,
"Currency": "USD"
}
}
}
}
这是我的Purchase
班:
public class Price
{
public int Amount { get; set; }
public string Currency { get; set; }
}
public class Purchase
{
public int Credits { get; set; }
public string Name { get; set; }
public int Price { get; set; }
}
这是我要反序列化的方式:
var countryToPurchases = JsonConvert.DeserializeObject<Dictionary<string, List<Purchase>>>(dataJSON);
这是我遇到的错误:
JsonReaderException:无效的属性标识符字符:{。路径“乌克兰”,第3行,位置4。 Newtonsoft.Json.JsonTextReader.ParseProperty()
我在这里想念什么?
答案 0 :(得分:4)
您在这里有两个问题:
[
{
"Ukraine": [
{
"Credits": 500,
"Name": "Clever goat",
"Price": {
"Amount": 100,
"Currency": "UAH"
}
},
{
"Credits": 1000,
"Name": "Smart hare",
"Price": {
"Amount": 190,
"Currency": "UAH"
}
}
]
},
{
"USA": [
{
"Credits": 500,
"Name": "Clever goat",
"Price": {
"Amount": 10,
"Currency": "USD"
}
},
{
"Credits": 1000,
"Name": "Smart hare",
"Price": {
"Amount": 19,
"Currency": "USD"
}
}
]
}
]
Price
属性的类型应为Price
,而不是int
。public class Purchase
{
public int Credits { get; set; }
public string Name { get; set; }
public Price Price { get; set; }
}
答案 1 :(得分:1)
请检查此json,看看是否可行:
{
"Ukraine": {
"Credits": 500,
"Name": "Clever goat",
"Price": {
"Amount": 100,
"Currency": "UAH"
}
},
"USA": {
"Credits": 500,
"Name": "Clever goat",
"Price": {
"Amount": 10,
"Currency": "USD"
}
}
}