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

标签 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# 提取中看到的那样,我已经尝试过使用数组和列表,但我无法让它工作。

对于第一个示例(带有数组),我得到一个 System.NullRefrenceException,而对于 List 示例,我得到几个错误,例如 Unable to cast object of type 'whereselectlistiterator '2 [Newtonsoft.JSON] 输入'system.iconvertible'

感谢任何提示帮助。

最佳答案

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

关于c# - 在 C# 中将 JSON 列表解析为 int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49341784/

相关文章:

c# - .NET 4.0 自动化/脚本化某些操作

c# - 如何从矢量或 ImageTargets 列表生成随机目标

c# - wpf 绑定(bind)到客户端不显示名称

c# - 如何在同一个 JSON 对象中反序列化不同的 NodaTime LocalDate 模式

c# - 将 JSON 反序列化为对象时出现问题

c# - 多线程集合锁类型

c# - 如何跳过 Json.Net 中 IEnumerable 类型的默认 JavaScript 数组序列化?

c# - 如果类具有 JsonExtensionData,如何使用 Json.NET 订购属性?

c# - 每次我打开代码时,newtonsoft json 包都需要重新安装

c# - 在 C# 中调用扩展方法的不同方式