Ahmed Jalal Ahmed Jalal - 1 year ago 106
JSON Question

Read specific object data from json

I want to get specific object data from json from url the following code give me. i need the second object 'EmailAddressSuffices'
enter image description here

WebRequest request = WebRequest.Create(
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();

Answer Source

Using JSON.Net you can deserialize the JSON response easily:

Solution 1

1. Create a class to map your JSON into:

public class ResponseObject

    public string Name { get; set; }

    public string LoginUrl { get; set; }

    public string LogoutUrl { get; set; }

    public string ImageUrl { get; set; }

    public IList<string> EmailAddressSuffixes { get; set; }

2. Deserialize your JSON using JsonConvert.Deserialize<ResponseObject>()

var myresponse = JsonConvert.DeserializeObject<List<ResponseObject>>(responseFromServer);
string email = myresponse[1].EmailAddressSuffixes[0];

Solution 2

If you don't want to bother with derializing the entire thing then you can do this:

JArray array = JArray.Parse(responseFromServer);
string q = array[1]["EmailAddressSuffixes"][0].ToString();

But you should make sure that your object has the right format (and the right number of items in the array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download