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;
    }
}
3

1 Answer 1

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}");
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @nbokmans. You saved my time. I was trying for this from yesterday. one more question How can I iterate through ChildObject?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.