3

I'm new to C#, I'm calling a service that is returning an encoded json response :

{"GetResult":["123"]}

In my code, I want to get 123. I wrote the following :

String response_after_parsing = JObject.Parse(response).SelectToken("GetResult").ToString();
Console.WriteLine(response_after_parsing);

The string that's being displayed in the console is the following :

["123"]

I've searched about this issue but I couldn't find the solution, any help please ?

4
  • SelectToken("GetResult") you're selecting the content of this key, so the return is correct Commented Aug 5, 2016 at 9:02
  • Yes but I only want 123 not ["123"] Commented Aug 5, 2016 at 9:03
  • 1
    Possible duplicate of How can I parse JSON with C#? Commented Aug 5, 2016 at 9:03
  • 2
    Treat it like an array and you will be OK Commented Aug 5, 2016 at 9:04

2 Answers 2

2

The GetResult is an array so you need to access individual items within it:

var response_after_parsing = JObject.Parse(response).SelectToken("GetResult")[0].ToString();

Alternatively you may use JsonConvert.DeserializeObject() but again access individual items within the array:

var response_after_parsing = ((dynamic)JsonConvert.DeserializeObject(response)).GetResult[0];
Sign up to request clarification or add additional context in comments.

Comments

0
        var response_after_parsing = JObject.Parse("{'GetResult':['123']}");
        var data =response_after_parsing["GetResult"][0]; // use like this 

or

        var response_after_parsing = JObject.Parse(response).SelectToken("GetResult[0]").ToString();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.