我有一个包含数组的JSON字符串,无法反序列化。我想拆分,以便每次尝试崩溃时都可以访问产品列表及其代码和数量。像这样返回Json字符串:
{
"transaction_id": "88",
"store_id": "3",
"cashier_id": null,
"loyalty_account": null,
"transaction_time": "1382027452",
"total_amount": "99.45",
"items": {
"1239219274": "1",
"3929384913": "1"
},
"payments": {
"cc": "99.45"
}
}
我希望将它分开:
{
"transaction_id": "88",
"store_id": "3",
"cashier_id": null,
"loyalty_account": null,
"transaction_time": "1382027452",
"total_amount": "99.45"
}
和
{
"1239219274":"1",
"3929384913":"1"
}
和
{
"cc": "99.45"
}
答案 0 :(得分:3)
编辑:已更新,以反映您的修改。
这不是一个JSON数组,它是一个JSON对象,它基本上是一个字典的值。
JSON数组序列化如下,方括号 [] :
{
"name":"Outer Object",
"items": [
{
"name":"Item #1"
},
{
"name":"Item #2"
},
{
"name":"Item #3"
}
]
}
您应该花几分钟时间学习Json.NET,这将为您处理细节。
以下是我可以将该字符串反序列化为对象的方法:
public class Transaction
{
[JsonProperty("transaction_id")]
public int Id { get; set; }
[JsonProperty("store_id")]
public int StoreId { get; set; }
[JsonProperty("cashier_id")]
public int? CashierId { get; set; }
[JsonProperty("loyalty_account")]
public string LoyaltyAccount { get; set; }
[JsonProperty("transaction_time")]
public int TransactionTime { get; set; }
[JsonProperty("total_amount")]
public decimal TotalAmount { get; set; }
[JsonProperty("items")]
public Dictionary<string, string> Items { get; set; }
[JsonProperty("payments")]
public Dictionary<string, string> Payments { get; set; }
}
然后我可以简单地写一下:
Transaction transaction = JsonConvert.DeserializeObject<Transaction>(json);
答案 1 :(得分:2)
首先,你的json字符串有一个错误,你可以使用在线验证器验证它,如: http://jsonlint.com/
Parse error on line 9:
... "1239219274": "1""3929384913": "1"
-----------------------^
Expecting '}', ':', ',', ']'
然后对于数组,他们有这种布局:
a : [1,2,3,4,5]