User5590
User5590

Reputation: 1435

Deserialize JSON array in c#

I have developed service which returns JSON string. Return string is as below:

string result = [{"ID":"1","ProductName":"Canon"},{"ID":"2","ProductName":"HP"}];

Now i want to deserialize above JSON string.

I have tried with below examples, but unable to do it. Getting error for all.

Dictionary<string, string> data = JsonConvert.DeserializeObject<Dictionary<string, string>>(result);

Dictionary<string, Dictionary<string, string>> data = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(result);

string[][] data = JsonConvert.DeserializeObject<string[][]>(result);

var serialize = new JavaScriptSerializer();
string[] resultArray = serialize.Deserialize<string[]>(result);

can anyone please help me out?

Upvotes: 1

Views: 118

Answers (3)

Florian Schmidinger
Florian Schmidinger

Reputation: 4692

For example:

class Program
{
    static void Main(string[] args)
    {
        string json = @"[{""ID"":""1"",""ProductName"":""Canon""},{""ID"":""2"",""ProductName"":""HP""}]";
        IEnumerable<Product> result =  JsonConvert.DeserializeObject<IEnumerable<Product>>(json);
    }   
}

class Product
{
    public int ID { get; set; }
    public string ProductName { get; set; }
}

If you want a dictionary:

IDictionary<int, string> dict = result.ToDictionary(product => product.ID, product => product.ProductName);

Upvotes: 2

Mahesh
Mahesh

Reputation: 8892

There are two ways to achieve what you want either create concrete class to store your values

public class MyJsonValueClass
{
    [JsonProperty(PropertyName = "ID")]
    public int Productid { get; set; }

    [JsonProperty(PropertyName = "ProductName ")] 
    public string Name { get; set; }
}

List<MyJsonValueClass> jsonData = JsonConvert.DeserializeObject<List<MyJsonValueClass>>(json);

Otherwise use the List<Dictionary<string,string>> list of dictionary will get the data if you don't want to create the class for it.

List<Dictionary<string,string>> dataFromJson = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(json);

Upvotes: 2

RagtimeWilly
RagtimeWilly

Reputation: 5445

Create a class to represent each element:

public class TestClass
{
    public int ID { get; set; }

    public string ProductName { get; set; }
}

The deserialize into TestClass[].

You can then use .ToDictionary() if you need it in that format:

Dictionary<int, string> lookup = deserializedArray.ToDictionary(k => k.Id, v => v.ProductName);

Upvotes: 0

Related Questions