1

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?

1
  • try creating a class and declare it as [JsonObject], then setting [JsonProperty("ID") string ID {get;set;} and [JsonProperty("ProductName") string productname {get;set;} Commented Feb 27, 2015 at 7:47

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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);

1 Comment

With approach the concrete class or dictionary list ?
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.