Reputation: 193
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;
}
}
Upvotes: 0
Views: 156
Reputation: 5757
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}");
}
}
Upvotes: 3