74

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 :)

Gourav
  • 2,746
  • 5
  • 28
  • 45
caknia
  • 1,221
  • 2
  • 13
  • 24

18 Answers18

77

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"));
}
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
Saad Asad
  • 2,528
  • 3
  • 20
  • 27
31

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.

JohnK
  • 6,865
  • 8
  • 49
  • 75
begrossi
  • 318
  • 4
  • 5
13
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;
}
Ignacio Lago
  • 2,432
  • 1
  • 27
  • 33
toddsalpen
  • 411
  • 4
  • 9
  • 3
    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. – indivisible Jun 05 '14 at 09:18
  • 2
    Checking if "jsonArray" is null after using it - is wrong as you might get NPE before the check itself. – android developer Nov 29 '14 at 23:50
12

TERRIBLE TERRIBLE TERRIBLE hack:

String[] arr = jsonArray.toString().replace("},{", " ,").split(" ");
drew moore
  • 31,565
  • 17
  • 75
  • 112
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()]);
Bhushan Bhangale
  • 10,921
  • 5
  • 43
  • 71
5

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

YouBee
  • 1,981
  • 1
  • 15
  • 16
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);
        }
Visruth
  • 3,430
  • 35
  • 48
  • hmm, I would like if the code is for dynamic data.. but thank you for your answer... :) – caknia Apr 08 '13 at 05:00
  • @andikurnia You have to get the dynamic data in `s`. please accept the answer if it works for you. – Visruth Apr 08 '13 at 06:25
  • I think this would fail if there were escaped brackets (\[) within the JSON. – Michael Munsey Oct 24 '14 at 21:31
  • @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. – Visruth Oct 25 '14 at 05:29
1

There you go:

String tempNames = jsonObj.names().toString();  
String[] types = tempNames.substring(1, tempNames.length()-1).split(","); //remove [ and ] , then split by ','
Wops
  • 983
  • 9
  • 23
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());
    }
Leo
  • 1,102
  • 2
  • 11
  • 18
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;
}
Zon
  • 18,610
  • 7
  • 91
  • 99
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());});
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);
Itération 122442
  • 2,644
  • 2
  • 27
  • 73
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()]);
}
ucMedia
  • 4,105
  • 4
  • 38
  • 46
1

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());
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"];
MUGABA
  • 751
  • 6
  • 7
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(","));
}
Januka samaranyake
  • 2,385
  • 1
  • 28
  • 50
  • 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. – Joe C Jan 29 '17 at 08:15
  • Incomplete answer. If you must provide answers then include and explanation and the extra utils – Mbuodile Obiosio Apr 05 '20 at 10:44
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

Cjo
  • 1,265
  • 13
  • 19
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());
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56