分隔包含对象的JSON字符串 [英] Separating a JSON string that contains object
问题描述
我有一个包含数组的JSON字符串,无法将其反序列化.我想拆分一下,以便每次尝试崩溃时都可以访问产品列表及其代码和数量.返回Json字符串,如下所示:
I have a JSON string that contains an array and it is unable to be deserialized. I would like to split so that I can access a list of products and their codes and quantities, each time I try it crashes. The Json string is returned like so:
{
"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"
}
}
我希望将其分为以下部分:
I would like it to be separate it into:
{
"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"
}
推荐答案
编辑:已更新以反映您的编辑.
EDIT: Updated to reflect your edit.
这不是JSON数组,而是一个JSON对象,它基本上是值的字典.
That is not a JSON array, that is a JSON object which is basically a dictionary of values.
JSON数组如下所示用方括号 [] 进行序列化:
A JSON array is serialized like the following with square brackets [ ]:
{
"name":"Outer Object",
"items": [
{
"name":"Item #1"
},
{
"name":"Item #2"
},
{
"name":"Item #3"
}
]
}
您可能应该花几分钟学习 Json.NET ,它将处理有关以下内容的详细信息你.
You should probably just spend a few minutes learning Json.NET which will take care of the details for you.
这是我可以将该字符串反序列化为对象的方法:
Here's how I can deserialize that string to an object:
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);
这篇关于分隔包含对象的JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!