Brendan Vogt
Brendan Vogt

Reputation: 26018

How to map a JSON value to a model property of a different name

How do you map a JSON property value to a model property of a different name using the HttpClient library using the .NET 4.5.1 framework and C#?

I am using the API from Weather Underground, and I created a console app just to test it out before I make the move to an ASP.NET MVC 5 web app.

static void Main(string[] args)
{
     RunAsync().Wait();
}

static async Task RunAsync()
{
     string _address = "http://api.wunderground.com/api/{my_api_key}/conditions/q/CA/San_Francisco.json";

     using (var client = new HttpClient())
     {
          try
          {
               HttpResponseMessage response = await client.GetAsync(_address);
               response.EnsureSuccessStatusCode();

               if (response.IsSuccessStatusCode)
               {
                    Condition condition = await response.Content.ReadAsAsync<Condition>();
               }
               Console.Read();
          }
          catch (HttpRequestException e)
          {
               Console.WriteLine("\nException Caught!");
               Console.WriteLine("Message :{0} ", e.Message);
          }
     }
}

My model classes to here I need the data populated:

public class Condition
{
     public Response Response { get; set; }
}

public class Response
{
     public string Terms { get; set; }
}

My partial JSON result:

{
     "response": {
          "version":"0.1",
          "termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
          "features": {
               "conditions": 1
          }
     }
}

This is a very basic example, buy how do I map the termsofservice value returned in the JSON to the Terms property in my response class? If possible I would like to stay in the bounds of the libraries used above, and not resolve to a 3rd party library like JSON.NET. If it can't be done then I will look into a 3rd party library.

I can probably have classes with properties with the same name as the data properties returned in the JSON, but I like to stick to best practices when naming properties and the properties need to have decent names.

Upvotes: 4

Views: 6755

Answers (1)

Stirrblig
Stirrblig

Reputation: 259

Maybe a bit too late, but for future reference.

You can map the json variable names by using the DataMember attribute from System.Runtime.Serialization. Mark the class as a DataContract. Note that with this approach every variable that you want to map from the json string must have the DataMember attribute, not only the ones with custom mapping.

using System.Runtime.Serialization;

[DataContract]
public class Response
{
    [DataMember(Name = "conditions")]
    public string Terms { get; set; }

    [DataMember]
    public string Foo { get; set; }

    public int Bar { get; set; } // Will not be mapped
}

Upvotes: 14

Related Questions