can’t seem to find an elegant way to deal with this!
lets say i have a method that returns a json array like this [“3”,“4”,“5”] as a string in Unity
how do i read or work with each item (3, 4, and 5) individually? (with each item as an integer, not string)
You’d need to do a bit of string manipulation. Likely you’d need to use a few different methods such as String.Trim, String.Replace, String.Split, and your choice of method to convert the string to an int (Such as Int.Parse).
Thanks for the reply! But how do i say pick the second item from this json array? its only a string and not ‘json’
string response = " ["3","4","5"] "
doesn’t seem like response[1] would return “4”
You’d first have to start stripping out characters, so would start with a Trim to remove the brackets. After that you’d probably want to Replace all the quotes with nothing (same with the backslashes if they’re literally in the string), leaving you with just three numbers separated by commas. At that point you use Split to break the three numbers into an Array.
hey thank you so much it was exactly what i needed!
sample code if anyone is wondering:
public string[] arrayOfString;
string response = "[\"1\",\"2\",\"3\"]" // alternatively you would get this when json array returned ["1","2","3"]
response = response.Trim('[', ']'); // "1","2","3"
response = response.Replace("\"", ""); // 1,2,3
arrayOfString = response.Split(','); // becomes an array of string
arrayOfString[0] // returns 1
or
public Int[] arrayOfInt;
string response = "[\"1\",\"2\",\"3\"]" // alternatively you would get this when json array returned ["1","2","3"]
response = response.Trim('[', ']'); // "1","2","3"
response = response.Replace("\"", ""); // 1,2,3
arrayOfInt = Array.ConvertAll(response.Split(','), int.Parse); // to create array of integers from string
arrayOfInt[0] // returns 1
1 Like