Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting Information from json string and add it to a list in C#

Tags:

json

c#

.net

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) by
var 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.

like image 553
Saikat halder Avatar asked Jul 24 '18 00:07

Saikat halder


1 Answers

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

like image 110
John Wu Avatar answered Sep 23 '22 21:09

John Wu