1

I have a json file as following:

"Steps":[
{"divisor":"13","dividend":"47","product":"39","quotient":"3","remainder":"8"},

{"divisor":"8","dividend":"13","product":"8","quotient":"1","remainder":"5"},

{"divisor":"5","dividend":"8","product":"5","quotient":"1","remainder":"3"},

{"divisor":"3","dividend":"5","product":"3","quotient":"1","remainder":"2"},

{"divisor":"2","dividend":"3","product":"2","quotient":"1","remainder":"1"},

{"divisor":"1","dividend":"2","product":"2","quotient":"2","remainder":"0"}

]

I want to read this in C# and convert it to list of array. Please help.

3
  • 1
    list of array ??? array or list??? Commented Jun 8, 2015 at 11:39
  • It should be list of objects Commented Jun 8, 2015 at 11:39
  • Wouldn't you want to convert it into a List<Operation> or something similar, where Operation has properties of Divisor, Dividend etc? (It seems odd that all those values are in strings, mind you...) Commented Jun 8, 2015 at 11:40

2 Answers 2

4

It is very easy, use json.net

public void GetJson()
{
    using (StreamReader r = new StreamReader("filename.json"))
    {
        string data = r.ReadToEnd();
        List<Step> steps = JsonConvert.DeserializeObject<List<Step>>(data);
    }
}

public class Step
{
    public int divisor { get; set; }
    public int dividend { get; set; }
    public int product { get; set; }
    public int quotient { get; set; }
    public int remainder { get; set; }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Actually, it is a list of objects. {} are objects in JSON, and [] are arrays. There are no "lists" in JSON. This is how it should be deserialized using Json.NET library:

public class Step
{
    public int divisor { get; set; }
    public int dividend { get; set; }
    public int product { get; set; }
    public int quotient { get; set; }
    public int remainder { get; set; }
}

public class StepsResponse
{
    public Step[] Steps { get; set; } // It can be a List<Step>
}

// ... 

JsonConvert.DeserializeObject<StepsResponse>(jsonString);

By the way, your JSON is invalid. It should be arounded by curly braces like

{
    "Items": ...
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.