Parsing JSON list to int array in c#

我们两清 提交于 2019-12-25 00:55:03

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/49341784/parsing-json-list-to-int-array-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!