2

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.

frenchie
  • 51,731
  • 109
  • 304
  • 510

3 Answers3

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

List<int> theList = (
  from string s in theArray.Split(',') 
  select Convert.ToInt32(s)
).ToList<int>();
essedbl
  • 520
  • 1
  • 7
  • 19
  • ok, thanks. I have another instance where I need to convert to a list of floats but the Convert. method doesn't show floats in the intellisense. The numbers are timezones and some timezones are 3.5 for instance; is using a float the best option and if so, how do I create a list of floats? – frenchie May 04 '11 at 18:35
  • One more thing, you might want to add a bit of error protection, such as using TryParse: List theList = (from string s in theArray.Split(',') select int.TryParse(s,out element) ? element : 0 ).ToList(); – essedbl May 04 '11 at 18:48
1

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

Community
  • 1
  • 1
manojlds
  • 290,304
  • 63
  • 469
  • 417
0

You can use the split method:

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

items[0] == "1" // true
Tejs
  • 40,736
  • 10
  • 68
  • 86
  • I think this is step one, but it still leaves the elements in the array as strings. – essedbl May 04 '11 at 18:33
  • In that case, all you have to do is call `parseInt(value)` on each element of the array and assign it back to the array. JavaScript is flexible that unless you need it to be an integer exactly, 1 == "1". The same is not the case for 1 === "1". – Tejs May 04 '11 at 18:35
  • ahhh... Yes, very true... I assumed he was doing this in C#, on the back end... But yes in javascript you are correct... – essedbl May 04 '11 at 18:39