Asp.NET HttpClient with custom JsonConverter

521 views Asked by At

Hi I have the following code to get data from a REST service:

HttpResponseMessage response;
                    response = client.GetAsync("CatalogUpdate/" + sessionId).Result;

                    if (response.IsSuccessStatusCode)
                    {
                        catalogs = response.Content.ReadAsAsync<List<Models.CatalogInfo>>().Result;
                    }

My CatalogInfo class is:

public class CatalogInfo
    {
        public CatalogInfo(int id,string name,string date)
        {
            this.ID = id;
            this.Name = name;
            this.Date = date;

        }
        public int ID { get; set; }
        public string Name { get; set; }
        public string Date { get; set; }

    }

And the jSON that Im getting from the REST service is:

{"error":false,"locations":[{"ID":"3","ABC":"XC","Description":"Rome","Status":"1"},{"ID":"4","CD1":"XH","Description":"Italy","Status":"1"}]}

I want to map the jSON to my CatalogInfo class, is there a way to do this?

1

There are 1 answers

0
Lloyd On

The easiest option here is to use Json.NET and to create classes that represent the expected JSON, so for example:

class Location
{

   public string ID { get; set; }
   public string Description { get; set; }
}

class JSONResponse
{

    [JsonProperty("error")]
    public bool Error { get; set; }

    [JsonProperty("locations")]
    public Location[] Locations { get; set; }

}

We don't have to implement every property as Json.NET will just ignore what isn't there.

Then deserialize the response. In your case you're using HttpResonseMessage so something like this:

JSONResponse response = JsonConvert.DeserializeObject<JSONResponse>(
    await response.Content.ReadAsStringAsync()
);

You can then use LINQ to convert the locations over to your object:

CatalogInfo[] catalog = response.Locations.Select(loc => new CatalogInfo(
    loc.ID,
    loc.Description,
    String.Empty
)).ToArray();