将JSON列表解析为C#中的int数组 [英] Parsing JSON list to int array in c#

查看:297
本文介绍了将JSON列表解析为C#中的int数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法将数字的JSON列表读取到c#int []数组中.

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

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

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

从JSON文件中提取:

Extract from JSON file:

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

我在c#中尝试过的事情:

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

和:

// 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#摘录中可以看到,我已经尝试过使用数组和列表,但是我无法使其正常工作.

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

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

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.

推荐答案

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

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

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

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

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

并将整个对象反序列化为

and deserialize whole object as

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

这篇关于将JSON列表解析为C#中的int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆