简体   繁体   中英

C# Parsing Json Array

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 ?

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];
        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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM