3

I'm having trouble reading a JSON list of numbers into a c# int[] array.

I've tried several suggestions from SO, but none have worked. How would I go about this using JSON.net?

Extract from JSON file:

    {
        "course": "Norsk",
        "grades": [6, 3, 5, 6, 2, 8]
    }

What I've tried in c#:

// Reads the JSON file into a single string
string json = File.ReadAllText(jfile);
Console.WriteLine(json);

// Parsing the information to a format json.net can work with
JObject data = JObject.Parse(json);

JToken jToken = data.GetValue("grades");
jGrades = jToken.Values<int>().ToArray();

and:

// Reads the JSON file into a single string
string json = File.ReadAllText(jfile);
Console.WriteLine(json);

// Parsing the information to a format json.net can work with
JObject data = JObject.Parse(json);

for (int o = 0; o < 6; o++) {
    var grades = from p in data["Info"[i]] select (int)p["grades"[o]];
    jGrades.Add(Convert.ToInt32(grades));
}

As you can see from the c# extracts, I've tried with both arrays and lists, but I can't get it to work.

With the first example (with an array) I get a System.NullRefrenceException, while with the List example, I get several errors, such as Unable to cast object of type 'whereselectlistiterator'2 [Newtonsoft.JSON] to type 'system.iconvertible'

Any help of tips are appreciated.

Hagland
  • 61
  • 1
  • 1
  • 7

2 Answers2

7

JObject.Parse(json) is your root object

JObject.Parse(json)["grades"] is the list/array

All you have to do is : converting the items to appropriate type

var list = JObject.Parse(json)["grades"].Select(x => (int)x).ToArray();

You can also declare a class

public class RootObject
{
    public string course { get; set; }
    public List<int> grades { get; set; }
}

and deserialize whole object as

var myobj = JsonConvert.DeserializeObject<RootObject>(json);
var grade = myobj.grades[0];
Eser
  • 12,346
  • 1
  • 22
  • 32
  • Thanks, I tried your first solution, but end up getting a **System-ArgumentNullException** error. And if this worked how would I go about accessing this info seeing as it is a `var` and not an array? Can I index it and add it to a list? Such as: `var list`... `grades.Add(list[i]);`? – Hagland Mar 18 '18 at 14:58
  • @Hagland **a)** above codes work with the json in your question, **b)** https://stackoverflow.com/questions/4307467/what-does-var-mean-in-c – Eser Mar 18 '18 at 17:53
  • 1
    thanks read up on `var`, but no, the code doesn't work: https://imgur.com/a/wuXHw – Hagland Mar 18 '18 at 21:04
  • @Hagland `but no, the code doesn't work` I tested above code twice (You can do it by yourself too) . Post your **real** code and json. I am pretty sure you use a different json which is not similar to the one in question ). – Eser Mar 18 '18 at 21:21
  • The only difference is that all the JSON is wrapped in an "Info" list, but I haven't needed to include the ["Info"] in any other statements of the working parts of the code. – Hagland Mar 18 '18 at 21:26
  • 1
    @Hagland So you think this difference is not important!!. OK good luck. Whenever you decide to ask a good question we will be here – Eser Mar 18 '18 at 21:28
  • No, I didn' think to include it as I haven't needed to use that part of the JSON structure to access the "course" or "grades" information in other parts of the C# code. – Hagland Mar 18 '18 at 21:34
  • 1
    @Hagland do you think `jobj["someprop"]` will find the values anywhere in json. Json is a hierarchical representation and the without knowing the whole structure a correct answer can not be given... If you don't want to post the real json, then open the docs and read them. This is all you can get from us with the info you have provided. – Eser Mar 18 '18 at 21:40
  • As I said above, the only difference is a wrapper. `"Info": [ { "course" : "Norsk", "grades" : [x, x, x, x, x, x] }, ...` – Hagland Mar 18 '18 at 22:38
4

I would typically define a class with the relevant properties and simply convert the object.

public class CourseReport
{
     public string Course { get; set; }
     public ICollection<int> Grades { get; set; }
}

// Reads the JSON file into a single string
string json = File.ReadAllText(jfile);
Console.WriteLine(json);

// Parsing the information to a format json.net can work with
var courseReport = JsonConvert.DeserializeObject<CourseReport>(json);

foreach (var grade in courseReport.Grades)
{
     Console.WriteLine(grade);
}
tvanfosson
  • 524,688
  • 99
  • 697
  • 795