0

I have been using NewtonSoft JSON Convert library to parse and convert JSON string to C# objects. I am unable to convert it into C# object because I cant make a C# class out of this JSON string.

Here is the JSON string:

{  
   "appId":"G9RNVJYTS6SFY",
   "merchants":{  
      "RZX9YMHSMP6A8":[  
         {  
            "objectId":"A:G9RNVJYTS6SFY",
            "type":"DELETE",
            "ts":1522736100111
         }
      ],
      "MNOVJT2ZRRRSC":[  
         {  
            "objectId":"A:G9RNVJYTS6SFY",
            "type":"CREATE",
            "ts":1522736100111
         }
      ]
   },
   ... and so on
}

The names RZX9YMHSMP6A8 and MNOVJT2ZRRRSC change from request to request

USED

var dict = JsonConvert.DeserializeObject<Dictionary<string, RootObject>>(JSON);

I got exception while this line is executed

Error converting value "G9RNVJYTS6SFY" to type 'RootObject'. Path 'appId', line 1, position 24.

public class Merchant
{
    public string objectId
    {
        get;
        set;
    }
    public string type
    {
        get;
        set;
    }
    public long ts
    {
        get;
        set;
    }
}

public class Merchants
{
    public List<Merchant> merchant
    {
        get;
        set;
    }
}

public class RootObject
{
    public string appId
    {
        get;
        set;
    }
    public Merchants merchants
    {
        get;
        set;
    }
}
dbc
  • 104,963
  • 20
  • 228
  • 340
07405
  • 193
  • 4
  • 14
  • did you validated the attribute names & data contract? can you share the RootObject code? – yossico Apr 03 '18 at 07:16
  • 1
    Possible duplicate of [Parsing JSON with dynamic properties](https://stackoverflow.com/questions/29190670/parsing-json-with-dynamic-properties) – Fabjan Apr 03 '18 at 07:31
  • And also a dup of [How can I parse a JSON string that would cause illegal C# identifiers?](https://stackoverflow.com/a/24536564) and [Deserializing JSON when key values are unknown](https://stackoverflow.com/a/24901245). – dbc Apr 03 '18 at 07:35

1 Answers1

3

You can convert this json to c# class structure using a Dictionary to hold the merchants (where the ID is the string key):

public class RootObject
{
    public string AppId { get; set; }
    public Dictionary<string, List<ChildObject>> Merchants { get; set; }
}

public class ChildObject
{
    public string ObjectId { get; set; }
    public string Type { get; set; }
    public long Ts { get; set; }
}

You can then loop over the childobjects like so:

foreach (var kvp in rootObject.Merchants) 
{
    var childObjects = kvp.Value;
    foreach (var childObject in childObjects) {
        Console.WriteLine($"MerchantId: {kvp.Key}, ObjectId: {childObject.ObjectId}, Type: {childObject.Type}");
    }
}
nbokmans
  • 5,492
  • 4
  • 35
  • 59
  • Thank you @nbokmans. You saved my time. I was trying for this from yesterday. one more question How can I iterate through ChildObject? – 07405 Apr 03 '18 at 07:37