Reputation: 1251
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 :)
Upvotes: 77
Views: 312138
Reputation: 891
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"];
Upvotes: 1
Reputation: 32690
TERRIBLE TERRIBLE TERRIBLE hack:
String[] arr = jsonArray.toString().replace("},{", " ,").split(" ");
Upvotes: 10
Reputation: 348
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.
Upvotes: 34
Reputation: 29
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());
Upvotes: 2
Reputation: 5496
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()]);
}
Upvotes: 1
Reputation: 2071
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
Upvotes: 8
Reputation: 2972
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);
Upvotes: 1
Reputation: 11050
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());
Upvotes: 0
Reputation: 2528
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"));
}
Upvotes: 78
Reputation: 33
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());});
Upvotes: 1
Reputation: 1351
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
Upvotes: 0
Reputation: 19918
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;
}
Upvotes: 1
Reputation: 519
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;
}
Upvotes: 14
Reputation: 2597
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(","));
}
Upvotes: 0
Reputation: 1120
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());
}
Upvotes: 1
Reputation: 993
There you go:
String tempNames = jsonObj.names().toString();
String[] types = tempNames.substring(1, tempNames.length()-1).split(","); //remove [ and ] , then split by ','
Upvotes: 1
Reputation: 3450
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);
}
Upvotes: 3
Reputation: 10987
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()]);
Upvotes: 8