How to parse JSON objects with numeric keys using

2019-02-27 04:59发布

问题:

I have an object like below to be deserialized in C#. I am wondering how I can parse it. I tried following this example here, but am stumped on how I can get my class to recognize the key of each object (the 2 and the 3 below).

The JSON string below basically represents 2 transactions. I would like to convert each transaction representation into a Transaction object and put it into an array of Transaction object.

{
    "2": {
        "id": "2",
        "user_id": "59",
        "offer_id": "1234"
    },
    "3": {
        "id": "3",
        "user_id": "59",
        "offer_id": "1234"
    }
}

Here are my classes:

public class Transactions
{
    // what goes here since the "key" field is always different?
}

public class Transaction
{
    public int id { get; set; }
    public int user_id { get; set; }
    public int offer_id { get; set; }
}

回答1:

It can be done with the JObject in JSON.Net library.

var transactions = JObject.Parse(json).PropertyValues()
                                      .Select(o => o.ToObject<Transaction>());

This should do the trick.



回答2:

Using the JavaScriptSerializer, you can handle this by deserializing into a Dictionary<string, Transaction>. From there you can convert it to an array pretty easily if you need to.

Example code:

string json = @"
{
    ""2"": {
        ""id"": ""2"",
        ""user_id"": ""59"",
        ""offer_id"": ""1234""
    },
    ""3"": {
        ""id"": ""3"",
        ""user_id"": ""59"",
        ""offer_id"": ""1234""
    }
}";

var serializer = new JavaScriptSerializer();
var dict = serializer.Deserialize<Dictionary<string, Transaction>>(json);
var transactions = dict.Select(kvp => kvp.Value).ToArray();

foreach (Transaction t in transactions)
{
    Console.WriteLine(string.Format(
        "id: {0}, user_id: {1}, offer_id: {2}", t.id, t.user_id, t.offer_id));
}