How to deserialize Json String and get keys from object using c#?

This is my code

""{\n  \"data\": [\n    {\n      \"listid\": \"\",\n      \"name\": \"\"\n    }\n  ]\n}""

In the above string was coming from server. I want to deserialize the string and get keys from array of objects. I tried using JsonConvert.Deserialization with Dictionary but it throws an exception. I also tried JObject and JArray. I want to get listId, name keys.

Upvotes: 0

Views: 4265

Answers (3)

Abdul Mateen Mohammed
Abdul Mateen Mohammed

Reputation: 1894

You can use Newtonsoft.Json library in C#

You need to create the corresponding Classes with the matching property names as that of the json array in C# in order to deserialize the json string to C# objects.

See the following code.

namespace StackOverflow.Test
{
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Linq;

    class Program
    {
        static void Main(string[] args)
        {
            var json = "{\n  \"data\": [\n    {\n      \"listid\": \"123\",\n      \"name\": \"Name\"\n    }\n  ]\n}";
            var lists = JsonConvert.DeserializeObject(json, typeof(Lists)) as Lists;
            var list = lists.Data.FirstOrDefault();

            Console.WriteLine("Name: " + list.Name);
            Console.WriteLine("List Id: " + list.ListId);

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }

    class Lists
    {
        public List<Info> Data { get; set; }
    }

    class Info
    {
        public string ListId { get; set; }

        public string Name { get; set; }
    }
}

Upvotes: 2

I got Solution, following code works fine

string json = "{\n  \"data\": [\n    {\n      \"listid\": \"\",\n      \"name\": \"\"\n    }\n  ]\n}";
        var jss = new JavaScriptSerializer();
        List<string> li = new List<string>();
        dynamic jsondata = jss.Deserialize<dynamic>(json);
        foreach (string key in jsondata["data"][0].Keys)
        {
            li.Add(key);
        }

Upvotes: 2

Slicc
Slicc

Reputation: 3435

Have you tried to deserialise to your own type? This works for me:

    public class Program
{
    public static void Main(string[] args)
    {
        string deser = "{\n  \"data\": [\n    {\n      \"listid\": \"\",\n      \"name\": \"\"\n    }\n  ]\n}";

        var obj = JsonConvert.DeserializeObject<MyCollection>(deser);


    }
}


public class MyType
{
    [JsonProperty("listid")]
    public string ListId { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }
}

public class MyCollection
{
    [JsonProperty("data")]
    public List<MyType> Data { get; set; }
}

Upvotes: 3

Related Questions