如何在C#中将Json对象转换为数组 [英] How to Convert Json Object to Array in C#

查看:569
本文介绍了如何在C#中将Json对象转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将JSON对象转换为C#数组.

I am trying to convert a JSON object in to C# array.

这是我从服务器webrequest响应中获取的JSon:

this is the JSon I Getfrom the Server webrequest response:

string result = sr.ReadToEnd(); // this line get me response 
result = {
    "subjects": [{
        "subject_id": 1,
        "subject_name": "test 1",
        "subject_class": 4,
        "subject_year": "2015",
        "subject_code": "t-1"
    },{
        "subject_id": 2,
        "subject_name": "test 2",
        "subject_class": 5,
        "subject_year": "",
        "subject_code": "t-2"
    }]
};

dynamic item = JsonConvert.DeserializeObject<object>(result);  

string iii = Convert.ToString(item["subjects"]);

我想获取主题并将其保存在数组中,以便将其用于其他目的.

I want to Get the Subjects and Save them in Array so i can use them for other purpose.

我在Method中使用了这些,但是总是得到空值.

I use these to Method but always got the empty values.

List<subjects> subject1 = (List<subjects>)JsonConvert.DeserializeObject(iii, typeof(List<subjects>));

subjects[] subject2 = JsonConvert.DeserializeObject<subjects[]>(iii);

请帮助我解决这个问题.

Please Help Me to Solve this.

我的学科课是..

class subjects
{
    public int id { get; set; }
    public string name { get; set; }
    public int class_name { get; set; }
    public string year { get; set; }
    public string code { get; set; }
}

推荐答案

属性名称将不匹配,因为您的主题类没有JSON对象具有的'subject_'前缀.最简单的解决方法是更改​​您的属性名称,如Ali的答案所示.万一您需要保持属性名称不变,还可以使用JsonProperty属性来更改序列化名称(也许有一种更通用的方式使用某种转换器,但并不认为需要的属性数量它)

The property names won't match as is, because you subjects class don't have the 'subject_' prefix the JSON object has. Easiest fix is to change your property names as shown in Ali's answer. Just in case you need to keep your property names as is, you can also use a JsonProperty attribute to alter the serialization names (perhaps there's a more generic way using some sort of converter, but didn't think the amount of properties needed it)

    class subjects
    {
        [JsonProperty("subject_id")]
        public int id { get; set; }
        [JsonProperty("subject_name")]
        public string name { get; set; }
        [JsonProperty("subject_class")]
        public int class_name { get; set; }
        [JsonProperty("subject_year")]
        public string year { get; set; }
        [JsonProperty("subject_code")]
        public string code { get; set; }
    }

如果您根本不需要根主题,也可以跳过它而无需动态学习,也可以跳过诸如此类的额外课程:

If you never need the root subjects you can also skip it without dynamic or an extra class with something like:

subjects[] arr = JObject.Parse(result)["subjects"].ToObject<subjects[]>();

(JObject是名称空间Newtonsoft.Json.Linq的一部分)

(JObject is part of the namespace Newtonsoft.Json.Linq )

这篇关于如何在C#中将Json对象转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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