简体   繁体   中英

How to Convert Json Object to Array in C#

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

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.

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

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

and

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

Please Help Me to Solve this.

And my Subject Class is..

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

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 is part of the namespace Newtonsoft.Json.Linq )

You need to create a structure like this:

public class Subjects
{
    public List<Subject> subjects {get;set;}
}

public class Subject
{
    public string subject_id {get;set;}
    public string subject_name {get;set;}
}

Then you should be able to do:

Subjects subjects = JsonConvert.DeserializeObject<Subject>(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM