How to convert Json object to array in C #

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

this is JSon's answer i getfrom server:

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 objects and store them in an array so that I can use them for other purposes.

I use them for a method, but I always get empty values.

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

      

and

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

      

Please help me solve this.

And my subject class ...

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

      

+3


source to share


2 answers


The property names will not match as you have a class that does not have the "subject_" prefix that has a JSON object. The simplest fix is ​​to change the property names as shown in Ali's answer. Just in case you need to keep your property names as they are, you can also use the attribute JsonProperty

to change the serialization names (maybe there is a more general way to use some kind of converter, but didn't think the number of properties it needed)

    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 root objects, you can also skip it without a dynamic or extra class with something like:



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

      

( JObject

is part of the namespace Newtonsoft.Json.Linq

)

0


source


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:

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

      

0


source







All Articles