Kyle
Kyle

Reputation: 2379

Serializing array of JSON objects from JSON response

I have a json response that looks like this:

"corps":
[
{
"id": "1007",
"company_id": "1007",
"org_name": "My organization 1",
"org_addr1": "123 W. 1234 S.",
"org_addr2": "",
},
{
"id": "1008",
"org_name": "My organization 2",
"org_addr1": "123 W. 1234 S.",
"org_addr2": "",
}
]

I have successfully gotten a single response into my HCO object properly using:

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(HCO));
HCO Company = (HCO)serializer.ReadObject(response.Content.ReadAsStreamAsync().Result);

This works well, but I'm trying to get all elements under corps. So I thought of trying something like this:

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(HCO));
HCO element = (HCO)serializer.ReadObject(response.Content.ReadAsStreamAsync().Result);
Companies.Add(element);

But this simply doesn't work. How do I parse the json result and then serialize each element in the response?

HCO Class:

public class HCO
    {
        public int id { get; set; }
        public int comapny_id { get; set; }
        public string org_name { get; set; }
        public string org_addr1 { get; set; }
        public string org_addr2 { get; set; }
    }

Upvotes: 0

Views: 673

Answers (1)

Yanire Romero
Yanire Romero

Reputation: 482

You can wrap up the HCO class in a Response like this:

public class HCOResponse
{
    public List<HCO> corps {get; set;}
}

And then try to deserialize the json using DataContractJsonSerializer like this:

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(HCOResponse));
Companies = (HCOResponse)serializer.ReadObject(response.Content.ReadAsStreamAsync().Result);

Hope it helps.

EDIT: (from feedback)

HCOResponse hco_resp = (HCOResponse)serializer.ReadObject(response.Content.ReadAsStreamAsync().Result);
Companies = hco_resp.corps;

Upvotes: 2

Related Questions