c# - How to map a JSON value to a model property of a different name -
how map json
property value model property of different name using httpclient
library using .net 4.5.1
framework , c#
?
i using api weather underground, , created console app test out before make move 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 here need 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 basic example, buy how map termsofservice value returned in json terms property in response class? if possible stay in bounds of libraries used above, , not resolve 3rd party library json.net
. if can't done 3rd party library.
i can have classes properties same name data properties returned in json, stick best practices when naming properties , properties need have decent names.
maybe bit late, future reference.
you can map json variable names using datamember attribute system.runtime.serialization. mark class datacontract. note approach every variable want map json string must have datamember attribute, not ones 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; } // not mapped }
Comments
Post a Comment