问题
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"
}
and
{
"1239219274":"1",
"3929384913":"1"
}
and
{
"cc": "99.45"
}
回答1:
EDIT: Updated to reflect your edit.
That is not a JSON array, that is a JSON object which is basically a dictionary of values.
A JSON array is serialized like the following with square brackets [ ]:
{
"name":"Outer Object",
"items": [
{
"name":"Item #1"
},
{
"name":"Item #2"
},
{
"name":"Item #3"
}
]
}
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; }
}
Then I can simply write:
Transaction transaction = JsonConvert.DeserializeObject<Transaction>(json);
回答2:
First of all you json string has an error you can validate it using an online validator like : http://jsonlint.com/
Parse error on line 9:
... "1239219274": "1""3929384913": "1"
-----------------------^
Expecting '}', ':', ',', ']'
And then for arrays they have this layout :
a : [1,2,3,4,5]
And using C# you can use JSON.Net if using javascript you can use jQuery or YUI
来源:https://stackoverflow.com/questions/19434500/separating-a-json-string-that-contains-object