Owais Iqbal
Owais Iqbal

Reputation: 35

How to convert Json to Array c#

I have been trying to convert Json response to C# Array and the thing is Json goes up from my head I dont understand its structure as its a mess for me. here is the example response I have as Json

{
   "status":"ok",
   "urls":{
      "phone":[
         {
            "url":"tel:+9230154XXXXX",
            "uri":"+9230154XXXXX"
         }
      ],
      "sms":{
         "url":"sms:+9230154XXXXX",
         "uri":"+9230154XXXXX"
      },
      "vcf":"https:\/\/www.eac.com\/i2\/ajax\/item\/vcf\/"
   },
   "limitExceeded":false
}

Now all i want from this Json sms:+9230154XXXXX this value. I am using Newtonsoft.Json in this example. Bellow is what I have tried so far

JObject jObject = JObject.Parse(json);
JToken jphone = jObject["urls"];
number = (string)jphone["phone"]["sms"];

Upvotes: 1

Views: 129

Answers (2)

Sebastian Münster
Sebastian Münster

Reputation: 575

I never really worked with Newtonsoft.Json but the following should work for you:

JToken token = JToken.Parse(json);
string number = (string)token.SelectToken("urls.sms.url")

Upvotes: 0

Orel Eraki
Orel Eraki

Reputation: 12196

Usage:

jObject["urls"]["phone"].ToObject<PhoneEntry[]>()

Class:

public class PhoneEntry {
    [JsonProperty("url")]
    public string Url { get; set; }

    [JsonProperty("uri")]
    public string Uri { get; set; }
}

Upvotes: 2

Related Questions