Convert JSONArray to String Array

JavaAndroidJson

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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.

Solution 3 - Java

shameless hack:

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

Solution 4 - Java

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

Solution 5 - Java

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

Solution 6 - Java

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

Solution 7 - Java

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

Solution 8 - Java

There you go:

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

Solution 9 - Java

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

Solution 10 - Java

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

Solution 11 - Java

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

Solution 12 - Java

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

Solution 13 - Java

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

Solution 14 - Java

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

Solution 15 - Java

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

Solution 16 - Java

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

Solution 17 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionandikurniaView Question on Stackoverflow
Solution 1 - JavaSaad AsadView Answer on Stackoverflow
Solution 2 - JavabegrossiView Answer on Stackoverflow
Solution 3 - Javadrew mooreView Answer on Stackoverflow
Solution 4 - JavatoddsalpenView Answer on Stackoverflow
Solution 5 - JavaBhushan BhangaleView Answer on Stackoverflow
Solution 6 - JavaYouBeeView Answer on Stackoverflow
Solution 7 - JavaVisruthView Answer on Stackoverflow
Solution 8 - JavaWopsView Answer on Stackoverflow
Solution 9 - JavaLeoView Answer on Stackoverflow
Solution 10 - JavaZonView Answer on Stackoverflow
Solution 11 - JavaucMediaView Answer on Stackoverflow
Solution 12 - JavaJanuka samaranyakeView Answer on Stackoverflow
Solution 13 - JavaCjoView Answer on Stackoverflow
Solution 14 - JavaSegualexView Answer on Stackoverflow
Solution 15 - JavaSamuel PhilippView Answer on Stackoverflow
Solution 16 - JavaItération 122442View Answer on Stackoverflow
Solution 17 - JavaFurkan UyanikView Answer on Stackoverflow