简体   繁体   中英

How to convert a JSON array to an array of string values

I'm try to parse some JSON like this:

{
   "results": [
       "MLU413843206",
       "MLU413841098",
       "MLU413806325",
       "MLU413850890",
       "MLU413792303",
       "MLU413843455",
       "MLU413909270",
       "MLU413921617",
       "MLU413921983",
       "MLU413924015",
       "MLU413924085"
   ]
}

All is fine until I try to obtain the values themselves, for example:

 // The JSON is shown above
 var jsonResp = JObject.Parse(json);    
 var items = jsonResp["results"].Children();

I don't know how to obtain the values, each converted to string. Does somebody know how to do this?

You're halfway there. You can use the Select() method in the System.Linq namespace to project the IEnumerable<JToken> returned from the Children() method into an IEnumerable<string> . From there you can loop over the values using foreach , or put the values into a List<string> using ToList() (or both).

string json = @"
{
    ""results"": [
        ""MLU413843206"",
        ""MLU413841098"",
        ""MLU413806325"",
        ""MLU413850890"",
        ""MLU413792303"",
        ""MLU413843455"",
        ""MLU413909270"",
        ""MLU413921617"",
        ""MLU413921983"",
        ""MLU413924015"",
        ""MLU413924085""
    ]
}";

JObject jsonResp = JObject.Parse(json);
List<string> items = jsonResp["results"].Children()
                                        .Select(t => t.ToString())
                                        .ToList();
foreach (string item in items)
{
    Console.WriteLine(item);
}

Fiddle: https://dotnetfiddle.net/Jcy8Ao

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