I'm getting data from a web service that returns a JSON response. This is my code:
WebClient client = new WebClient();
var result = client.DownloadString("http://some url");
JObject obj = JObject.Parse(result);
// Location l = new Location();
// l.city = obj["ad"][2]; error here
At this point it returns a result, but I am getting an error:
Cannot implicitly convert type 'Newtonsoft.Json.Linq.JToken' to 'string'
I would like some assistance getting the returned data into my variable in the model.
This is my JSON:
{
data: [
{
address_obj: {
street1: "9518 Front Beach Road",
street2: "",
city: "Panama City Beach",
state: "Florida",
country: "United States",
postalcode: "32407",
address_string: "9518 Front Beach Road, Panama City Beach, FL 32407"
},
You can add those class models to your app, and deserialize the json to it, you can use various types of deseriallizers, personally I like newtonsoft's json.net, here are the classes:
After that deserialize the response to AddressObj and access the city property
The JSON represents an outer object containing a
data
array of objects, with each item containing anaddress_obj
object which then has string properties. So theJToken
indexer syntax you use has to match that hierarchy, including using the correct property names. Also, when retrieving the value from aJToken
you need to cast it to the correct type.You can get the city like this, where
i
is the index of the location you want:However, if all you're doing is populating model objects, it is probably simpler to deserialize directly to those using
JsonConvert.DeserializeObject<T>
rather than manually populating them usingJTokens
. For example, if your classes are defined like this:Then you can deserialize directly to them like this: