0

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?

3
  • How do you want to map considering they have different properties and seem unrelated? Commented Jun 24, 2015 at 18:40
  • I want to map ID with ID and Name with Description Commented Jun 24, 2015 at 18:42
  • This [question][1] looks similar to what you are looking for. [1]: stackoverflow.com/questions/2246694/… Commented Jun 24, 2015 at 20:23

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.