Arh Hokagi Arh Hokagi - 5 months ago 22
JSON Question

map unknown properties with json.net

im working with the lib: Json.NET.
i have a json file with the data below

{
"Product":
{
"random Key1": "some text",
"random Key2": "some text",
"random Key3": "some text"
},
"TestSequence":
{
"random Key4": "Some text"
}
}


i can deserialize the json file but i can't map json properties to a class properties

public class Product
{
[JsonExtensionData]
private IDictionary<string, JToken> _additionalData { get; set; }
}
public class MyData
{
public Product Product { get; set; }
}
------main programme ----
using (StreamReader r = new StreamReader(@"\Base File\Base.json"))
{
json = r.ReadToEnd();
MyData invoice = JsonConvert.DeserializeObject<MyData>(json);

string result = JsonConvert.SerializeObject(invoice);
}


how can i access the value of "random Key1" property in my code?

Answer

One possibility is to use a normal dictionary:

public class MyData
{
    public IDictionary<string, string> Product { get; set; }
}

and then once you deserialize you could loop through all the keys and values:

var invoice = JsonConvert.DeserializeObject<MyData>(json);
foreach (var item in invoice.Product)
{
    Console.WriteLine("key: {0}, value: {1}", item.Key, item.Value);
}

Of course in order to access a value directly you could need to know the key which is how dictionaries work:

Console.WriteLine(invoice.Product["random Key2"]);