I have successfully parsed JSONArray into list by using the below function
public List<Integer> ParseJson(String json, List<Integer> myList) {
JSONArray jsonArray = null;
try {
JSONObject mainJson = new JSONObject(json);
jsonArray = mainJson.getJSONArray("result");
myList = new ArrayList<Integer>();
for (int i = 0; i < jsonArray.length(); i++) {
myList.add(Integer.parseInt(jsonArray.get(i).toString()));
}
// System.out.println(myList);
} catch (JSONException e) {
e.printStackTrace();
}
Collections.reverse(myList);
return myList;
}
Now I need the List into reverse order. What would be the optimized way to do that?
Before you edited your question it seemed like you wanted to reverse the JSON array, append it to "myList" and return the result. If that's true, try this:
public List<Integer> ParseJson(String json, List<Integer> myList) {
JSONArray jsonArray = null;
try {
JSONObject mainJson = new JSONObject(json);
jsonArray = mainJson.getJSONArray("result");
List<Integer> reverseListFromJson = new ArrayList<Integer>();
for (int i = 0; i < jsonArray.length(); i++) {
reverseListFromJson.add(jsonArray.getInt(i));
}
Collections.reverse(reverseListFromJson);
myList.addAll(reverseListFromJson);
} catch (JSONException e) {
e.printStackTrace();
}
return myList;
}
[1,2,3,5,23,534,23]: Your JSONArray already contains ints, no need to convert.
JSONArray jsonarray = getTheJSONArrayFromSomewhere();
Log.d(TAG, jsonarray.toString(4)); // for debugging purposes. Check the contents of the jsonarray
List<Integer> list = new ArrayList<Integer>();
for (int i = jsonarray.length() - 1; i >= 0; i--)
list.add(jsonarray.getInt(i));
or this
JSONArray jsonarray = getTheJSONArrayFromSomewhere();
Log.d(TAG, jsonarray.toString(4)); // for debugging purposes. Check the contents of the jsonarray
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < jsonarray.length(); i++)
list.add(jsonarray.getInt(i));
Collections.reverse(list);
That does reverse your Integer List, assuming your JSONArray is filled correctly, and contains ints. Also, I omitted try/catch, you'll have to add those.
use below code to do this
ArrayList<Element> tempElements = new ArrayList<Element>(mElements);
Collections.reverse(tempElements);
hope it will work for you
Have you tried using:
ArrayList<Element> tempElements = new ArrayList<Element>(mElements);
Collections.reverse(tempElements);
Related
Okay, I'm struggling here. I am getting the following JSON formated string from my php server (called "result") (edited! I was missing a curly brace at the end):
{"L1":[{"UserName":"User1","Avatar":"1"},{"UserName":"User2","Avatar":"2"},{"UserName":"User3","Avatar":"3"}],"L2":[{"UserName":"User4","Avatar":"4"},{"UserName":"User5","Avatar":"5"}]}
I'm trying to extract an ArrayList with the Avatar numbers from the L1 object(?). But I get an error
org.json.JSONException: Value
[{"UserName":"User1","Avatar":"1"},{"UserName":"User2","Avatar":"2"},{"UserName":"User3","Avatar":"3"}]
at L1 of type org.json.JSONArray cannot be converted to JSONObject
Here's my code:
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = new JSONArray(jsonObject.getJSONObject("L1"));
ArrayList<Integer> arrList = new ArrayList<>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
arrList.add(json.getInt("Avatar"));
AvatarList = arrList;
}
}
String query_result = "SUCCESS";
if (query_result.equals("FAILURE")) {
} else {
setAvatars(AvatarList);
}
} catch (JSONException e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
If I use
jsonObject.getJSONArray("L1")
I get the same error.
Any suggestions?
Thanks in advance!
(edit: I made a mistake in the original post. There was a missing curly brace in the JSON string. Thanks to those who caught that)
Try the below one.Its working fine. I'm using json-simple-1.1.1 jar
String r="{\"L1\":[{\"UserName\":\"User1\",\"Avatar\":\"1\"},{\"UserName\":\"User2\",\"Avatar\":\"2\"},{\"UserName\":\"User3\",\"Avatar\":\"3\"}],\"L2\":[{\"UserName\":\"User4\",\"Avatar\":\"4\"},{\"UserName\":\"User5\",\"Avatar\":\"5\"}]}";
Object obj=JSONValue.parse(r);
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonArray = (JSONArray) jsonObject.get("L1");
ArrayList<Integer> arrList = new ArrayList<>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject json = (JSONObject) jsonArray.get(i);
arrList.add((Integer.parseInt((String) json.get("Avatar"))));
AvatarList = arrList;
}
}
String query_result = "SUCCESS";
if (query_result.equals("FAILURE")) {
} else {
setAvatars(AvatarList);
}
This ended up working for me if anyone stumbles upon this. I don't really understand why this worked and my original method didn't... something to do with JSONObjects vs JSONArrays vs Strings and things like [, {, }, and ] probably.
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = new JSONArray(jsonObject.getString("L1"));
ArrayList<Integer> arrList = new ArrayList<>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
arrList.add(json.getInt("Avatar"));
AvatarList = arrList;
}
}
I submit a query from my Java application, which upon running on Elasticsearch server returns the result in the form of a string. I want the result as a list of JSONObject objects. I can convert the string to a JSONObject using JSONObject jsonResponse = new JSONObject(responseString).
Is there any method by which I can get this in the form of a List<JSONObject>?
Instead of using JSONObject you may use JSONArray. If you really need to convert it to a List you may do something like:
List<JSONObject> list = new ArrayList<JSONObject>();
try {
int i;
JSONArray array = new JSONArray(string);
for (i = 0; i < array.length(); i++)
list.add(array.getJSONObject(i);
} catch (JSONException e) {
System.out.println(e.getMessage());
}
There is an answer of your question:
https://stackoverflow.com/a/17037364/1979882
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
This method is really easy and works too
try {
JSONObject jsonObject = new JSONObject(THESTRINGHERE);
String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonArray;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
// System.out.println(listdata);
} catch (Exception e) {
System.out.println(e.getMessage());
}
I have an JSON Array that looks like this
[["ONE","CAT",0],["TWO","DOG",0]]
And I want to make it into an ArrayList<List<String>>, I am trying to loop though it but can't get it to work.
I have tried
for (ArrayList arrayList: jsonArray) {
for (Object array : arrayList) {
}
}
But then I got a compilation error. I'm not able to loop through an Array of JSON Objects.
You can try this way -
try {
ArrayList<Object> _arrList = new ArrayList<Object>();
JSONArray _jArryMain = new JSONArray("YOUR_JSON_STRING");
if (_jArryMain.length()>0) {
for (int i = 0; i < _jArryMain.length(); i++) {
JSONArray _jArraySub = _jArryMain.getJSONArray(i);
_arrList.add(_jArraySub);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
First, Java does not like mixed types. If you are sure you can use List<List<String>> then keep reading.
I recommend using the Jackson Library and ObjectMapper#readTree.
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree("JSON CONTENT");
List<List<String>> convertedList = new ArrayList<List<String>>();
for (JsonNode arrNode : node) {
List<String> currList = new ArrayList<String>();
convertedList.add(currList);
for (JsonNode dataNode : arrNode) {
currList.add(dataNode.asText());
}
}
System.out.println(convertedList);
I guess this is what your looking for :
try {
ArrayList<ArrayList<Object>> mainarraylist = new ArrayList<ArrayList<Object>>();
JSONArray jsonarray = new JSONArray(yourstringjson);
if (jsonarray.length()>0) {
for (int i = 0; i < jsonarray.length(); i++) {
ArrayList<String> subarray;
JSONArray jsonsubarray = jsonarray.getJSONArray(i);
for (int i = 0; i < jsonsubarray.length(); i++) {
subarray = new ArrayList<String>;
jsonsubarray.add(jsonsubarray.get(i));
}
mainarraylist.add(jsonsubarray);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This will give you the result: mainarraylist.get(0).get(0) equals ONE
FYI: The code is not compiled, so there might some errors. This is an abstract for your solution.
you can use this code to solve your problems
String jsonValue = "[[\"ONE\",\"CAT\",0],[\"TWO\",\"DOG\",0]]";
try{
JSONArray array = (JSONArray) new JSONTokener(jsonValue).nextValue();
ArrayList<JSONArray> arrayList = new ArrayList<>();
arrayList.add(array);
for (int i=0;i<arrayList.get(arrayList.size()-1).length();i++) {
try {
JSONArray arr = arrayList.get(arrayList.size()-1).getJSONArray(i);
for (int j = 0; j < arr.length(); j++) {
System.out.println("Value = " + arr.get(j));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch (JSONException e){
}
1. try {
String abc = "[[\"ONE\",\"CAT\",0],[\"TWO\",\"DOG\",0]]";
JSONArray jsonarray = new JSONArray(abc);
if (jsonarray.length()>0) {
for (int i = 0; i < jsonarray.length(); i++) {
JSONArray jsonsubarray = jsonarray.getJSONArray(i);
for (int j = 0; j < jsonsubarray.length(); j++) {
Log.d("Value---->",""+jsonsubarray.get(j));
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
To parse a json array to a list of list i have created the following method.
public static List<List<String>> convertJsonToListofList(String json) throws Exception{
JSONArray jArray=new JSONArray(json);
List<List<String>> list = new ArrayList<List<String>>();
int length = jArray.length();
for(int i=0; i<length;i++) {
JSONArray array;
List<String> innerlist = new ArrayList<String>();
String innerJsonArrayString = jArray.get(i).toString();
JSONArray innerJsonArray = new JSONArray(innerJsonArrayString);
int innerLength = innerJsonArray.length();
for(int j=0;j<innerLength;j++){
String str = innerJsonArray.getString(j);
innerlist.add(str);
}
list.add(innerlist);
}
return list;
}
You have to call this method in this way:
try {
List<List<String>> listoflist = convertJsonToListofList("[[\"ONE\",\"CAT\",0],[\"TWO\",\"DOG\",0]]");
System.out.println(listoflist);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The output I have obtained is this one
07-09 13:00:42.268: I/System.out(19986): [[ONE, CAT, 0], [TWO, DOG, 0]]
I hope this is what you are looking for :)
Another Jackson approach.
ObjectMapper mapper = new ObjectMapper();
String json = "[[\"ONE\",\"CAT\",0],[\"TWO\",\"DOG\",0]]";
List<List<String>> output = new ArrayList<List<String>>();
JsonNode root = mapper.readTree(json);
for (JsonNode child : root) {
output.add(mapper.readValue(child.traverse(), new TypeReference<ArrayList<String>>(){}));
}
I have a webservice which returns a JSON array in this format:
[{"imageid":"3","userid":"1","imagepath":"SLDFJNDSKJFN","filterid":"1","dateadded":"2014-05-06 21:20:18.920257","public":"t"},
{"imageid":"4","userid":"1","imagepath":"dsfkjsdkfjnkjdfsn","filterid":"1","dateadded":"2014-05-06 21:43:37.642748","public":"t"}]
I need to get all the attributes seperately? How would I do this?
I know how to do it with JSONObject if there is just 1 thing being returned, but how does it work when multiple items are returned?
Thanks
try {
JSONArray jArray = new JSONArray(jsonString);
String s = new String();
for (int i = 0; i < jArray.length(); i++) {
s = jArray.getJSONObject(i).getString("imageid").toString();
s = jArray.getJSONObject(i).getString("userid").toString();
}
} catch (JSONException je) {
}
Create an Object class with all variables, create a List for this Object, add all objects in your JSONArray to the list, use the one you need.
List<YourObject> objList = new ArrayList<YourObject>();
JSONArray a = new JSONArray(response);
int size = a.length();
for (int i=0 ; i<size ; i++){
JSONObject aa = a.getJSONObject(i);
String id = aa.getString("imageid");
String userid = aa.getString("userid");
String imagepath = aa.getString("imagepath");
String filterid = aa.getString("filterid");
String dateadded = aa.getString("dateadded");
String publicText = aa.getString("public");
YourObject obj = new YourObject(id,userid,imagepath,filterid,dateadded,publicText);
objList.add(obj);
}
So what you are having here is some JSON objects inside a JSON array.
What you want to do is this:
JSONArray array = ...;
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
// Extract whatever you want from the JSON object.
}
I hope it helped.
You can use JSONArray to parse array of JSON response.
private void parseJsonArray(String response) {
try {
JSONArray array = new JSONArray(response);
for(int i=0;i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
String ImageId = jsonObject.getString("imageid");
Log.v("JSON Parser", "ImageId: "+ImageId);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Is there a way to convert JSON Array to normal Java Array for android ListView data binding?
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
If you don't already have a JSONArray object, call
JSONArray jsonArray = new JSONArray(jsonArrayString);
Then simply loop through that, building your own array. This code assumes it's an array of strings, it shouldn't be hard to modify to suit your particular array structure.
List<String> list = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
list.add( jsonArray.getString(i) );
}
Instead of using bundled-in org.json library, try using Jackson or GSON, where this is a one-liner. With Jackson, f.ex:
List<String> list = new ObjectMapper().readValue(json, List.class);
// Or for array:
String[] array = mapper.readValue(json, String[].class);
Maybe it's only a workaround (not very efficient) but you could do something like this:
String[] resultingArray = yourJSONarray.join(",").split(",");
Obviously you can change the ',' separator with anything you like (I had a JSONArray of email addresses)
Using Java Streams you can just use an IntStream mapping the objects:
JSONArray array = new JSONArray(jsonString);
List<String> result = IntStream.range(0, array.length())
.mapToObj(array::get)
.map(Object::toString)
.collect(Collectors.toList());
Use can use a String[] instead of an ArrayList<String>:
It will reduce the memory overhead that an ArrayList has
Hope it helps!
String[] stringsArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length; i++) {
parametersArray[i] = parametersJSONArray.getString(i);
}
I know that question is about JSONArray but here's example I've found useful where you don't need to use JSONArray to extract objects from JSONObject.
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
String jsonStr = "{\"types\":[1, 2]}";
JSONObject json = (JSONObject) JSONValue.parse(jsonStr);
List<Long> list = (List<Long>) json.get("types");
if (list != null) {
for (Long s : list) {
System.out.println(s);
}
}
Works also with array of strings
Here is a better way of doing it: if you are getting the data from API. Then PARSE the JSON and loading it onto your listview:
protected void onPostExecute(String result) {
Log.v(TAG + " result);
if (!result.equals("")) {
// Set up variables for API Call
ArrayList<String> list = new ArrayList<String>();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.get(i).toString());
}//end for
} catch (JSONException e) {
Log.e(TAG, "onPostExecute > Try > JSONException => " + e);
e.printStackTrace();
}
adapter = new ArrayAdapter<String>(ListViewData.this, android.R.layout.simple_list_item_1, android.R.id.text1, list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText( ListViewData.this, "Position :" + itemPosition + " ListItem : " + itemValue, Toast.LENGTH_LONG).show();
}
});
adapter.notifyDataSetChanged();
adapter.notifyDataSetChanged();
...
we starting from conversion [ JSONArray -> List < JSONObject > ]
public static List<JSONObject> getJSONObjectListFromJSONArray(JSONArray array)
throws JSONException {
ArrayList<JSONObject> jsonObjects = new ArrayList<>();
for (int i = 0;
i < (array != null ? array.length() : 0);
jsonObjects.add(array.getJSONObject(i++))
);
return jsonObjects;
}
next create generic version replacing array.getJSONObject(i++) with POJO
example :
public <T> static List<T> getJSONObjectListFromJSONArray(Class<T> forClass, JSONArray array)
throws JSONException {
ArrayList<Tt> tObjects = new ArrayList<>();
for (int i = 0;
i < (array != null ? array.length() : 0);
tObjects.add( (T) createT(forClass, array.getJSONObject(i++)))
);
return tObjects;
}
private static T createT(Class<T> forCLass, JSONObject jObject) {
// instantiate via reflection / use constructor or whatsoever
T tObject = forClass.newInstance();
// if not using constuctor args fill up
//
// return new pojo filled object
return tObject;
}
You can use a String[] instead of an ArrayList<String>:
Hope it helps!
private String[] getStringArray(JSONArray jsonArray) throws JSONException {
if (jsonArray != null) {
String[] stringsArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
stringsArray[i] = jsonArray.getString(i);
}
return stringsArray;
} else
return null;
}
We can simply convert the JSON into readable string, and split it using "split" method of String class.
String jsonAsString = yourJsonArray.toString();
//we need to remove the leading and the ending quotes and square brackets
jsonAsString = jsonAsString.substring(2, jsonAsString.length() -2);
//split wherever the String contains ","
String[] jsonAsStringArray = jsonAsString.split("\",\"");
To improve Pentium10s Post:
I just put the elements of the JSON array into the list with a foreach loop. This way the code is more clear.
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
jsonArray.forEach(element -> list.add(element.toString());
private String[] getStringArray(JSONArray jsonArray) throws JSONException {
if (jsonArray != null) {
String[] stringsArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
stringsArray[i] = jsonArray.getString(i);
}
return stringsArray;
} else
return null;
}
You can use iterator:
JSONArray exportList = (JSONArray)response.get("exports");
Iterator i = exportList.iterator();
while (i.hasNext()) {
JSONObject export = (JSONObject) i.next();
String name = (String)export.get("name");
}
I know that the question was for Java. But I want to share a possible solution for Kotlin because I think it is useful.
With Kotlin you can write an extension function which converts a JSONArray into an native (Kotlin) array:
fun JSONArray.asArray(): Array<Any> {
return Array(this.length()) { this[it] }
}
Now you can call asArray() directly on a JSONArray instance.
How about using java.util.Arrays?
List<String> list = Arrays.asList((String[])jsonArray.toArray())