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.

3 Answers 3

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

List<int> theList = (
  from string s in theArray.Split(',') 
  select Convert.ToInt32(s)
).ToList<int>();
Sign up to request clarification or add additional context in comments.

2 Comments

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?
One more thing, you might want to add a bit of error protection, such as using TryParse: List<int> theList = (from string s in theArray.Split(',') select int.TryParse(s,out element) ? element : 0 ).ToList<int>();
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

Comments

0

You can use the split method:

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

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

3 Comments

I think this is step one, but it still leaves the elements in the array as strings.
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".
ahhh... Yes, very true... I assumed he was doing this in C#, on the back end... But yes in javascript you are correct...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.