JSON Array to ArrayList<List<String>> - java

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

Related

Compare list of JSONArray in ArrayList

I have an ArrayList containing a list of JSONArrays
staffArray = new ArrayList<JSONArray>();
the JSONArray is in a form of this:
[
{
"id": "k40dn-dff02-mm1",
"name": "staff1",
"tel": "0123456789",
},
{
"id": "ch2mq-pmw01-ps6",
"name": "staff2",
"tel": "9876543210",
}
...
]
And the ArrayList will be containing different sizes of JSONArray.
Now I want to check in the ArrayList for each JSONArray, if they contain the same value for "id". So say that if the ArrayList has three different sizes of JSONArray, how can I tell the they each contain a JSONObject with the same value for "id" in it.
So far I have tried this to extract the string:
for(int i = 0; i < staffArray.size(); i++){
JSONArray jsonArray = new JSONArray();
jsonArray = staffArray.get(i);
for(int j = 0; j < jsonArray.length(); j ++){
JSONObject json = null;
try {
json = jsonArray.getJSONObject(j);
String id = json.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
If you would like to check for duplicate IDs in your ArrayList, you could do something like this:
ArrayList<JSONArray> staffArray = new ArrayList<>();
Set<String> ids = new HashSet<>();
for (JSONArray array : staffArray) {
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
if (!ids.add(obj.getString("id"))) {
// duplicate IDs found, do something
}
}
}
How about using group by to group the json arrays with same id something like this
public static void groupById(List<JSONArray> staffArray) {
Map<String, List<JSONArray>> jsonArraysById = staffArray.stream().collect(Collectors.groupingBy(jsonArray -> getIdFromJsonArray(jsonArray)));
jsonArraysById.forEach((id, arrays) -> {
System.out.println("Arrays with id " + id + " are " + arrays);
});
}
public static String getIdFromJsonArray(JSONArray jsonArray) {
String result = null;
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject json = null;
try {
json = jsonArray.getJSONObject(j);
result = json.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
return result;
}

Parse JSONArray present in generic ArrayList

I have some issue with JSONArray, As I am having a JSON data present in generic ArrayList but I don't have any idea that how to parse that json data and display in list, I am using org.json library
Below is my json data which is present in array list:
[{"story":"Gaurav Takte shared a link.","created_time":"2017-02-14T19:08:34+0000","id":"1323317604429735_1307213186040177"},{"story":"Gaurav Takte shared a link.","created_time":"2017-02-02T14:22:50+0000","id":"1323317604429735_1295671703860992"},{"message":"Hurray....... INDIA WON KABBADI WORLD CUP 2016","created_time":"2016-10-22T15:55:04+0000","id":"1323317604429735_1182204335207730"},{"story":"Gaurav Takte updated his profile picture.","created_time":"2016-10-21T05:35:21+0000","id":"1323317604429735_1180682575359906"},{"message":"Friends like all of you \u2026 I would love to keep forever.\n#oldmemories with # besties \n#happydays","story":"Gaurav Takte with Avi Bhalerao and 5 others.","created_time":"2016-10-21T05:33:55+0000","id":"1323317604429735_1180682248693272"},{"message":"\"सर्वांना गणेशचतुर्थीच्या हार्दीक शुभेच्छा.\nतुमच्या मनातील सर्व मनोकामना पूर्ण होवोत , सर्वांना\nसुख, समृध्दी, ऎश्वर्य,शांती,आरोग्य लाभो हीच\nबाप्पाच्या चरणी प्रार्थना. \"\nगणपती बाप्पा मोरया , मंगलमुर्ती मोरया !!!","story":"Gaurav Takte with Avi Bhalerao and 18 others.","created_time":"2016-09-05T05:06:58+0000","id":"1323317604429735_1133207030107461"}]
And here is my code:
ArrayList data_arr1= (ArrayList) ((Map) parsed.get("posts")).get("data"); JSONArray array = new JSONArray(data_arr1); for(int i = 0; i < array.length(); i++){ try { JSONObject obj = array.getJSONObject(i); Log.p(obj.toString()); } catch (JSONException ex) { ex.printStackTrace(); } }
So how can i parse this json using org.json library.
Here is the best solution of in-proper json response.
You can try this code I hope it works good..
String result = "Your JsonArray Data Like [{}]";
ArrayList<String> arrayList = new ArrayList<>();
try {
JSONArray jsonarray = new JSONArray(result);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String story = null;
try {
story = jsonobject.getString("story");
} catch (Exception e) {
e.printStackTrace();
}
String msg = null;
try {
msg = jsonobject.getString("message");
} catch (Exception e) {
e.printStackTrace();
}
String ct = jsonobject.getString("created_time");
String id = jsonobject.getString("id");
if (msg == null){
msg = "";
}
if (story == null){
story = "";
}
arrayList.add(story + msg + ct + id);
// Smodel is getter model
// arrayList.add(new Smodel(story, msg, ct, id));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Creating an ArrayList from a JSON Object

So I have a JSON just like the picture below stored as MYJSON--
My plan is to retrieve all the object from childObject0 and store them in an ArrayList so they can be processed later. So I did-
ArrayList<String> childLists = new ArrayList<String>();
try {
JSONArray childArray = MYJSON.getJSONArray("childObject0");
for (int i = 0; i<jArray.length(); i++
) {
//I lost it here! How can I append to `childList` from `childArray`?
}
} catch (JSONException e) {
e.printStackTrace();
}
Can't figure out how to append. Is this right approach? childObject0 is dynamic and the count changes time to time.
Thanks
Since each object in childObject0 is json, you can store it as an ArrayList<JSONObject>. That should make the objects easier to process than as Strings.
ArrayList<JSONObject> childList = new ArrayList<JSONObject>();
try {
JSONArray childArray = MYJSON.getJSONArray("childObject0");
for (int i = 0; i < childArray.length(); i++) {
childList.add(childArray.getJSONObject(i));
}
} catch (JSONException e) {
e.printStackTrace();
}

Android, cannot iterate through JSONArray inside for-loop

I'm trying the following to iterate through each JSONObject in an JSONArray but it's not working. I check the length of the JSONArray in the Log and it gives me the correct lenght, but I can't get the JSONObject at each element of the JSONArray. Also, each element should be a JSONObject with 8 key/value pairs. Any feedback is greatly appreciated, thanks.
if (getMyJSONArray() != null) {
newJSONArray = getMyJSONArray();
try {
// Did this because the JSONArray was inside a JSONArray
innerJSONArray = newJSONArray.getJSONArray(0);
} catch (JSONException e) {
e.printStackTrace();
}
if (innerJSONArray != null) {
// This gives me the right length
Log.i("innerJSONArray.length: ", String.valueOf(innerJSONArray.length()));
for (int i = 0; innerJSONArray.length() < 0; i++) {
try {
// This doesn't work
JSONObject jsonObject1 = innerJSONArray.getJSONObject(i);
// This doesn't work either
JSONObject jsonObject2 = new JSONObject(innerJSONArray.getString(i));
…(more code below to use if the part above works)
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
In your for loop innerJSONArray.length() < 0; should be i < innerJSONArray.length().
Then this line should work as expected:
JSONObject jsonObject1 = innerJSONArray.getJSONObject(i);

android reverse int array

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

Categories

Resources