1

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"];
4
  • Dont you have a class which matches your JSON? Serializing it will give you the required object easily Commented Feb 18, 2018 at 13:44
  • I dont have it. Commented Feb 18, 2018 at 13:46
  • I believe string number = (string)jphone["sms"]["uri"]; is what you attempted Commented Feb 18, 2018 at 13:48
  • @derloopkat Life saver man! Thanks alot. Commented Feb 18, 2018 at 13:54

2 Answers 2

2

Usage:

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

Class:

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

    [JsonProperty("uri")]
    public string Uri { get; set; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Fixed the little bug.
0

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.