77

I want to ask a question about converting a jsonArray to a StringArray on Android. Here is my code to get jsonArray from server.

try {
    DefaultHttpClient defaultClient = new DefaultHttpClient();
    HttpGet httpGetRequest = new HttpGet("http://server/android/listdir.php");
    HttpResponse httpResponse = defaultClient.execute(httpGetRequest);

    BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(),"UTF-8"));

    String json = reader.readLine();

    //JSONObject jsonObject = new JSONObject(json);
    JSONArray jsonArray = new JSONArray(json);
    Log.d("", json);

    //Toast.makeText(getApplicationContext(), json, Toast.LENGTH_SHORT).show();

} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

And this is the JSON.

[
    {"name": "IMG_20130403_140457.jpg"},
    {"name":"IMG_20130403_145006.jpg"},
    {"name":"IMG_20130403_145112.jpg"},
    {"name":"IMG_20130404_085559.jpg"},
    {"name":"IMG_20130404_113700.jpg"},
    {"name":"IMG_20130404_113713.jpg"},
    {"name":"IMG_20130404_135706.jpg"},
    {"name":"IMG_20130404_161501.jpg"},
    {"name":"IMG_20130405_082413.jpg"},
    {"name":"IMG_20130405_104212.jpg"},
    {"name":"IMG_20130405_160524.jpg"},
    {"name":"IMG_20130408_082456.jpg"},
    {"name":"test.jpg"}
]

How can I convert jsonArray that I've got to StringArray so I can get StringArray like this:

array = {"IMG_20130403_140457.jpg","IMG_20130403_145006.jpg",........,"test.jpg"};

Thank you for your help :)

5
  • Why do you want to do that and waste resources? Commented Apr 8, 2013 at 4:45
  • 2
    @Nezam, excuse me, what do you mean..? Commented Apr 8, 2013 at 4:50
  • Why would you want to convert a JSONArray which you showed to an ArrayList or an Array.Any special use? Commented Apr 8, 2013 at 4:51
  • 1
    yes, in spesification list it had to be stringArray... :( Commented Apr 8, 2013 at 4:58
  • stackoverflow.com/a/55691694/470749 was helpful for me. list.add(item.getAsString()); Commented Mar 22, 2021 at 16:16

18 Answers 18

78

Take a look at this tutorial. Also you can parse above json like :

JSONArray arr = new JSONArray(yourJSONresponse);
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
    list.add(arr.getJSONObject(i).getString("name"));
}
Sign up to request clarification or add additional context in comments.

3 Comments

this convert to Array List first, then I can convert again to StringArray, thank to give an idea... (y)
You can use list.add(arr.getString(i) just as well
Since the length of the array is known, the ArrayList should be constructed with an explicit size (e.g. new ArrayList<String>(arr.length()).
34

Simplest and correct code is:

public static String[] toStringArray(JSONArray array) {
    if(array==null)
        return new String[0];
    
    String[] arr=new String[array.length()];
    for(int i=0; i<arr.length; i++) {
        arr[i]=array.optString(i);
    }
    return arr;
}

Using List<String> is not a good idea, as you know the length of the array. Observe that it uses arr.length in for condition to avoid calling a method, i.e. array.length(), on each loop.

Comments

14
public static String[] getStringArray(JSONArray jsonArray) {
    String[] stringArray = null;
    if (jsonArray != null) {
        int length = jsonArray.length();
        stringArray = new String[length];
        for (int i = 0; i < length; i++) {
            stringArray[i] = jsonArray.optString(i);
        }
    }
    return stringArray;
}

2 Comments

Code only answers, while they may be correct, are rarely as informative as ones that also explain why. Consider adding some comments or an explanation to your post.
Checking if "jsonArray" is null after using it - is wrong as you might get NPE before the check itself.
10

TERRIBLE TERRIBLE TERRIBLE hack:

String[] arr = jsonArray.toString().replace("},{", " ,").split(" ");

2 Comments

this is insecure: [ { "name" : "},{" }, ... ]
the problem is, that, if some string contains json (like "},{"), it would be splitted too.
8

You can loop to create the String

List<String> list = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
    list.add( jsonArray.getString(i) );
}
String[] stringArray = list.toArray(new String[list.size()]);

Comments

8

Was trying one of the same scenario but found one different and simple solution to convert JSONArray into List.

import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

String jsonStringArray = "[\"JSON\",\"To\",\"Java\"]";                 
    
//creating Gson instance to convert JSON array to Java array
                   
    Gson converter = new Gson();                  
    Type type = new TypeToken<List<String>>(){}.getType();
    List<String> list =  converter.fromJson(jsonStringArray, type );

Give a try

Comments

3

Here is the code :

// XXX satisfies only with this particular string format
        String s = "[{\"name\":\"IMG_20130403_140457.jpg\"},{\"name\":\"IMG_20130403_145006.jpg\"},{\"name\":\"IMG_20130403_145112.jpg\"},{\"name\":\"IMG_20130404_085559.jpg\"},{\"name\":\"IMG_20130404_113700.jpg\"},{\"name\":\"IMG_20130404_113713.jpg\"},{\"name\":\"IMG_20130404_135706.jpg\"},{\"name\":\"IMG_20130404_161501.jpg\"},{\"name\":\"IMG_20130405_082413.jpg\"},{\"name\":\"IMG_20130405_104212.jpg\"},{\"name\":\"IMG_20130405_160524.jpg\"},{\"name\":\"IMG_20130408_082456.jpg\"},{\"name\":\"test.jpg\"}]";
        s = s.replace("[", "").replace("]", "");
        s = s.substring(1, s.length() - 1);
        String[] split = s.split("[}][,][{]");
        for (String string : split) {
            System.out.println(string);
        }

4 Comments

hmm, I would like if the code is for dynamic data.. but thank you for your answer... :)
@andikurnia You have to get the dynamic data in s. please accept the answer if it works for you.
I think this would fail if there were escaped brackets ([) within the JSON.
@Michael Munsey, It will not fail if the key or value contains [, but the result will not contain [, see s = s.replace("[", "").replace("]", "");. And, I have also mentioned satisfies only with this particular string format. This code should be improved based on @andikurnia's requirement.
2

The below code will convert JSON array to List

For example;

import org.json.JSONArray

String data = "YOUR_JSON_ARRAY_DATA";
JSONArray arr = new JSONArray(data);
List<String> list = arr.toList().stream().map(Object::toString).collect(Collectors.toList());

2 Comments

You should make it clear what this compared to the existing answers (which superficially look quite similar). It also doesn't look like you use data.
I am so sorry. I updated my answer. Thank you for feedback!
1

There you go:

String tempNames = jsonObj.names().toString();  
String[] types = tempNames.substring(1, tempNames.length()-1).split(","); //remove [ and ] , then split by ','

1 Comment

this is dangerous, cause there could be other occurrence of "," in the data
1

Using only the portable JAVA API. http://www.oracle.com/technetwork/articles/java/json-1973242.html


    try (JsonReader reader = Json.createReader(new StringReader(yourJSONresponse))) {
        JsonArray arr = reader.readArray();

        List<String> l = arr.getValuesAs(JsonObject.class)
            .stream().map(o -> o.getString("name")).collect(Collectors.toList());
    }

Comments

1

A ready-to-use method:

/**
* Convert JSONArray to ArrayList<String>.
* 
* @param jsonArray JSON array.
* @return String array.
*/
public static ArrayList<String> toStringArrayList(JSONArray jsonArray) {

  ArrayList<String> stringArray = new ArrayList<String>();
  int arrayIndex;
  JSONObject jsonArrayItem;
  String jsonArrayItemKey;

  for (
    arrayIndex = 0;
    arrayIndex < jsonArray.length();
    arrayIndex++) {

    try {
      jsonArrayItem =
        jsonArray.getJSONObject(
          arrayIndex);

      jsonArrayItemKey =
        jsonArrayItem.getString(
          "name");

      stringArray.add(
        jsonArrayItemKey);
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }

  return stringArray;
}

Comments

1

Bit late for an answer, but here's what I came up with using Gson:

for a jsonarray foo: [{"test": "bar"}, {"test": "bar2"}]

JsonArray foo = getJsonFromWherever();
String[] test = new String[foo.size()]
foo.forEach(x -> {test = ArrayUtils.add(test, x.get("test").getAsString());});

Comments

1

I do post an answer here for the question here that was closed even though the asnwers here helped, but were not sufficient.

So, this is in order to get a json array to a String[] using jsonsimple.

According to the (marvelous) decode examples and docs, JSONArrays are java List, so we can access List methods.

From there, is it possible to transform it to a String[] with the following:

    JSONObject assemblingTags = (JSONObject) obj.get("assembling-tags");
    JSONArray aTagsList = (JSONArray) assemblingTags.get("list");
    String[] tagsList = (String[]) aTagsList.stream().toArray(String[]::new);

Comments

1

And here is my solution, You may want to convert and merge more than a single array :

public static String[] multiJsonArrayToSingleStringArray(JSONArray... arrays) {
    ArrayList<String> list=new ArrayList<>();
    for (JSONArray array : arrays)
        for (int i = 0; i < array.length(); i++)
            list.add(array.optString(i));

    return list.toArray(new String[list.size()]);
}

Comments

1

I know this is probably late. I hope it will help someone.

When you have a string array that is stringfied. say something like this

String chars =  "["a","b","c"]";// Json stringfied string
List<String>charArray = (List<String>) JSON.parse(chars);

String[] stringArray = cars.toArray(new String[char.size()]);

There you go the array has something like this

 stringarray = ["a","b","c"];

Comments

0

You can input json array to this function get output as string array

example Input - { "gender" : ["male", "female"] }

output - {"male", "female"}

private String[] convertToStringArray(Object array) throws Exception {
   return StringUtils.stripAll(array.toString().substring(1, array.toString().length()-1).split(","));
}

2 Comments

While you may have solved this user's problem, code-only answers are not very helpful to users who come to this question in the future. Please edit your answer to explain why your code solves the original problem.
Incomplete answer. If you must provide answers then include and explanation and the extra utils
0

The below code will convert the JSON array of the format

[{"version":"70.3.0;3"},{"version":"6R_16B000I_J4;3"},{"version":"46.3.0;3"},{"version":"20.3.0;2"},{"version":"4.1.3;0"},{"version":"10.3.0;1"}]

to List of String

[70.3.0;3, 6R_16B000I_J4;3, 46.3.0;3, 20.3.0;2, 4.1.3;0, 10.3.0;1]

Code :

ObjectMapper mapper = new ObjectMapper(); ArrayNode node = (ArrayNode)mapper.readTree(dataFromDb); data = node.findValuesAsText("version"); // "version" is the node in the JSON

and use com.fasterxml.jackson.databind.ObjectMapper

Comments

0

You might want to take a look at JSONArray.toList(), which returns a List containing Maps and Lists, which represent your JSON structure. So you can use it with Java Streams like this:

JSONArray array = new JSONArray(jsonString);
List<String> result = array.toList().stream()
        .filter(Map.class::isInstance)
        .map(Map.class::cast)
        .map(o -> o.get("name"))
        .filter(String.class::isInstance)
        .map(String.class::cast)
        .collect(Collectors.toList());

This might just be useful even for more complex objects.

Alternatively you can just use an IntStream to iterate over all items in the JSONArray and map all names:

JSONArray array = new JSONArray(jsonString);
List<String> result = IntStream.range(0, array.length())
        .mapToObj(array::getJSONObject)
        .map(o -> o.getString("name"))
        .collect(Collectors.toList());

Comments

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.