[java] Convert JSONArray to String Array

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

This question is related to java android json

The answer is


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());
    }

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()]);

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


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

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


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;
}

There you go:

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

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

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);
        }

Simplest and correct code is:

public static String[] toStringArray(JSONArray array) {
    if(array==null)
        return null;

    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.


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());});

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;
}

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(","));
}

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());

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?