How to Convert Json Object to Array in C#

28,473

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 )

Share:
28,473
Awais
Author by

Awais

Updated on July 04, 2020

Comments

  • Awais
    Awais almost 4 years

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