How to get a string value from a JToken

The JSON represents an outer object containing a data array of objects, with each item containing an address_obj object which then has string properties. So the JToken indexer syntax you use has to match that hierarchy, including using the correct property names. Also, when retrieving the value from a JToken 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:

l.city = (string)obj["data"][i]["address_obj"]["city"];

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 using JTokens. For example, if your classes are defined like this:

public class RootObject
{
    [JsonProperty("data")]
    public List<Item> Data { get; set; }
}

public class Item
{
    [JsonProperty("address_obj")]
    public Location Location { get; set; }
}

public class Location
{
    [JsonProperty("street1")]
    public string Street1 { get; set; }
    [JsonProperty("street2")]
    public string Street2 { get; set; }
    [JsonProperty("city")]
    public string City { get; set; }
    [JsonProperty("state")]
    public string State { get; set; }
    [JsonProperty("country")]
    public string Country { get; set; }
    [JsonProperty("postalcode")]
    public string PostalCode { get; set; }
    [JsonProperty("address_string")]
    public string FullAddress { get; set; }
}

Then you can deserialize directly to them like this:

RootObject obj = JsonConvert.DeserializeObject<RootObject>(result);

Here is an example of how to get JToken and JArray as a string.

Use Formatting.None for simple formatting.

string json = "[\"a\", null, \"b\", null, null, null, 0,[],[[\"c\"], null,[0],[\"d\"]]]";
    JArray array = JArray.Parse(json);
    // array string
    string arrayStr = array.ToString(Newtonsoft.Json.Formatting.None);
    for (int i = 0; i < array.Count; i++)
    {
        JToken elem = array[i];
        // token string
        string jtokenStr = elem.ToString(Newtonsoft.Json.Formatting.None);
    }

Tags:

C#

Json

Json.Net