Saikat halder
Saikat halder

Reputation: 618

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

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.

Upvotes: 6

Views: 119

Answers (3)

Saurabh Agrawal
Saurabh Agrawal

Reputation: 649

The correct way to deserialize would be as below

var model = JsonConvert.DeserializeObject<Dictionary<string, Item>>(data);

In the code sample you have posted, your "user" class name is Item but you are trying to deserialize using "User" in your code. Also please note that you cannot directly directly deserialize data into users list as it is present as a value of some random strings.

var model = JsonConvert.DeserializeObject<user>(json);

For your code to deserialize correctly, your json format should be as below :

{
{
    "address": "Jessore",
    "name": "Dev"
},
{
    "address": "Bogra",
    "name": "Kumar Saikat"
}

}

Upvotes: 0

Kelly
Kelly

Reputation: 7183

Can use the nuget package Newtonsoft.Json. This code gives you what you are looking for:

  using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var json =
                "{\"JrPwbApfIHbQhCUmVIoiVJcPYv93\":{\"address\":\"Jessore\",\"name\":\"Dev\"}," +
                "\"iBRZAyn8TQTOgKTcByGOvJjL9ZB3\":{\"address\":\"Bogra\",\"name\":\"Kumar Saikat\"}}";


            var o = JsonConvert.DeserializeObject(json);

            var items = new List<Item>();

            foreach (dynamic x in o as IEnumerable)
            {
                var i = new Item();
                var y = x.First;
                i.Name = y.name.Value;
                i.Address = y.address.Value;
                items.Add(i);
            }
        }

        public class Item
        {
            public string Name { get; set; }
            public string Address { get; set; }
        }
    }
}

Your situation is a bit strange as those autocreated names like "JrPwbApfIHbQhCUmVIoiVJcPYv93" or else it's easier, but should be fairly easy code.

Keep in mind I use "dynamic" there which means problems will hit you at runtime NOT design time as it's not checked.

Upvotes: 0

John Wu
John Wu

Reputation: 52240

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

Upvotes: 6

Related Questions