在c#中将JSON列表解析为int数组

时间:2018-03-17 20:51:05

标签: c# json.net

我在将一个JSON数字列表读入c#int []数组时遇到了麻烦。

我已经尝试了SO的几个建议,但没有一个有效。 我将如何使用JSON.net进行此操作?

从JSON文件中提取:

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

我在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();

和:

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

正如你从c#extract中看到的那样,我已经尝试过使用数组和列表,但我无法让它工作。

使用第一个示例(带有数组),我得到一个 System.NullRefrenceException ,而使用List示例,我得到了几个错误,例如无法转换类型的对象whereselectlistiterator '2 [Newtonsoft.JSON]输入'system.iconvertible'

感谢任何提示帮助。

2 个答案:

答案 0 :(得分:3)

JObject.Parse(json)是您的根对象

JObject.Parse(json)["grades"]是列表/数组

您所要做的就是:将项目转换为适当的类型

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

您还可以声明一个类

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

并将整个对象反序列化为

var myobj = JsonConvert.DeserializeObject<RootObject>(json);
var grade = myobj.grades[0];

答案 1 :(得分:3)

我通常会定义一个具有相关属性的类,并简单地转换对象。

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