简体   繁体   中英

converting an array in a json string into a list

I have an array in a json string like this:

"TheArray": "1,2,3,4,5"

What's the best way convert this into a list of int?

Thanks.

string theArray = "1,2,3,4,5";

List<int> theList = (
  from string s in theArray.Split(',') 
  select Convert.ToInt32(s)
).ToList<int>();

Use JSON.Net or JavascriptSerializer, something like:

JArray jsonArray = JArray.Parse(jsonStr);

and then you can get out TheArray from that.

The TheArray in your question is not exactly a JSON array, so you will have to parse the string like other answers suggested after you get value of TheArray

http://www.nateirwin.net/2008/11/20/json-array-to-c-using-jsonnet/

http://james.newtonking.com/projects/json-net.aspx

Parsing JSON using Json.net

You can use the split method:

var items = myObj.TheArray.split(',');

items[0] == "1" // true

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