Android How To Convert Json Array To String Array
I have an app where I fetch data from server(json) in the form of array & by using the index i used in my app, like below. JSONObject topobj = new JSONObject(page); JSONObject
Solution 1:
This should help you.
Edit:
Maybe this is what you need:
ArrayList<String> stringArray = newArrayList<String>();
JSONArray jsonArray = newJSONArray();
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
stringArray.add(jsonObject.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
Solution 2:
Assume that you already have JSONArray jsonArray:
String[] stringArray = new stringArray[jsonArray.length()];
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
try {
String jsonString = jsonArray.getString(i);
stringArray[i] = jsonString.toString();
}
catch (JSONException e) {
e.printStackTrace();
}
}
Solution 3:
This I think is what you searching for
ArrayList<String> list = newArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
for (int i=0;i<jsonArray.length();i++){
list.add(jsonArray.get(i).toString());
}
Solution 4:
I just did this yesterday! If you're willing to use a 3rd party library then you can use Google GSON, with the additional benefit of having more concise code.
String json = jsonArray.toString();
Type collectionType = newTypeToken<Collection<String>>(){}.getType();
Collection<String> strings = gson.fromJson(json, collectionType);
for (String element : strings)
{
Log.d("TAG", "I'm doing stuff with: " + element);
}
You can find more examples in the user guide.
Solution 5:
Another elegant kotlin way:
val list = jsonArray.map { jsonElement -> jsonElement.toString() }
And just convert to array if needed
Post a Comment for "Android How To Convert Json Array To String Array"