How to parse JSON objects with numeric keys using JavaScriptSerializer

后端 未结 2 1180
旧巷少年郎
旧巷少年郎 2021-01-22 08:39

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 recog

2条回答
  •  攒了一身酷
    2021-01-22 09:01

    Using the JavaScriptSerializer, you can handle this by deserializing into a Dictionary. 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>(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));
    }
    

提交回复
热议问题