I am new in json. I want information of different users and add them to a dataGridView or dataTable or dataSet in c# (.net development). Information sample is (The json is valid):
{
"JrPwbApfIHbQhCUmVIoiVJcPYv93": {
"address": "Jessore",
"name": "Dev"
},
"iBRZAyn8TQTOgKTcByGOvJjL9ZB3": {
"address": "Bogra",
"name": "Kumar Saikat"
}
}
I want them like this :
User1 | Jessore | Dev
User2 | Bogra | Kumar Saikat
Even it would help if I could make a list for all of them.
I believe I was able to deserialise them (not sure at all) byvar model = JsonConvert.DeserializeObject<user>(json);
where user is a class.
public class Item
{
public string name;
public string address;
}
from this question-answer. From this tutorial I am able to get values if property is known. But in my case my property would be unknown, (string "User1","User2" would be random, since I will get them from a database). Any help and light on this matter would be greatly appreciated. Thank you in advance.
You're looking at a JSON dictionary, so just deserialize it as such:
public static Dictionary<string,Item> ParseJson(string source)
{
return JsonConvert.DeserializeObject<Dictionary<string,Item>>(source);
}
If you call it like this:
public static void Main()
{
var input = @"{'JrPwbApfIHbQhCUmVIoiVJcPYv93': {'address': 'Jessore','name': 'Dev' }, 'iBRZAyn8TQTOgKTcByGOvJjL9ZB3': {'address': 'Bogra','name': 'Kumar Saikat'}}";
var result = ParseJson(input);
foreach (var r in result)
{
Console.WriteLine("Key={0};Name={1};Address={2}", r.Key, r.Value.name, r.Value.address);
}
}
The output is:
Key=JrPwbApfIHbQhCUmVIoiVJcPYv93;Name=Dev;Address=Jessore
Key=iBRZAyn8TQTOgKTcByGOvJjL9ZB3;Name=Kumar Saikat;Address=Bogra
This example dumps the list to the console, but you could easily modify the for
loop to add to a list instead.
See my example on DotNetFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With