Creating an ArrayList from a JSON Object - java

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

Related

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

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

JSON Array to ArrayList<List<String>>

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

Returning a two dimensional array from a list is not indexing properly

Okay so I have successfully turned a list into a two dimensional array. The only problem is the output only indexes it once, so basically if I have 10 elements within each list that I want to add to a two dimensional array, the two dimensional array will have only one index with 'n' number of elements.
For example
I would like
{{1,2,3}, {4,5,6}, {7,8,9}}
Instead it is returning:
{1,2,3,4,5,6,7,8,9}
I took suggestions from:
Convert ArrayList into 2D array containing varying lengths of arrays
Here is my code:
public static Object[][] getOrderCreateTestCases(){
List<List<String>> list = new ArrayList<>();
List<String> values = new ArrayList<>();
try {
JSONArray jObject = (JSONArray)getClient().sendGet(String.format("get_cases/12&suite_id=136"));
for(Object obj : jObject){
JSONObject jObj = (JSONObject)obj;
values.add(jObj.get("title").toString());
values.add(jObj.get("id").toString());
values.add(jObj.get("custom_order_type").toString());
values.add(jObj.get("custom_product_type").toString());
values.add(jObj.get("custom_free_shipping").toString());
values.add(jObj.get("custom_billing_country").toString());
values.add(jObj.get("custom_shipping_country").toString());
list.add(values);
for(int i=0; i<list.size(); i++){
valuesString = new Object[list.get(i).size()][];
List<String> row = list.get(i);
valuesString[i] = row.toArray(new String[row.size()]);
//System.out.print(valuesString[i]);
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (APIException e) {
e.printStackTrace();
}
return valuesString;
}
I am working with DataProviders with TestNG and they require a return of a two dimensional Object array, which I can understand why. I am parsing out certain data from a JSON Array (json-simple), adding it to the list, and then converting to a two dimensional array. So let's say it grabs the info from ID=5546, then the next id=4987, next id=3847 and so on.. Any help would be greatly appreciated
UPDATED...
Okay so I think I see why it's doing what it's doing but I still do not know how to solve the problem. So basically as it loops and it begins the new set of data, then it needs to create a new array.
{{List1}, {List2}, {List3}}
I suppose getOrderCreateTestCases is your data provider.
If so could you try it this way?
public static Object[][] getOrderCreateTestCases() {
List<List<String>> list = new ArrayList<>();
List<String> values = new ArrayList<>();
try {
JSONArray jObject = (JSONArray) getClient().sendGet(
String.format("get_cases/12&suite_id=136"));
for (Object obj : jObject) {
try {
JSONObject jObj = (JSONObject) obj;
values.add(jObj.get("title").toString());
values.add(jObj.get("id").toString());
values.add(jObj.get("custom_order_type").toString());
values.add(jObj.get("custom_product_type").toString());
values.add(jObj.get("custom_free_shipping").toString());
values.add(jObj.get("custom_billing_country").toString());
values.add(jObj.get("custom_shipping_country").toString());
list.add(values);
} catch (Exception e) {
// Ignore
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (APIException e) {
e.printStackTrace();
}
valuesString = new Object[list.get(i).size()][];
for (int i = 0; i < list.size(); i++) {
List<String> row = list.get(i);
valuesString[i] = row.toArray(new String[row.size()]);
}
return valuesString;
}

How do I remove a specific element from a JSONArray?

I am building one app in which I request a PHP file from server. This PHP file returns a JSONArray having JSONObjects as its elements e.g.,
[
{
"uniqid":"h5Wtd",
"name":"Test_1",
"address":"tst",
"email":"ru_tst#tst.cc",
"mobile":"12345",
"city":"ind"
},
{...},
{...},
...
]
my code:
/* jArrayFavFans is the JSONArray i build from string i get from response.
its giving me correct JSONArray */
JSONArray jArrayFavFans=new JSONArray(serverRespons);
for (int j = 0; j < jArrayFavFans.length(); j++) {
try {
if (jArrayFavFans.getJSONObject(j).getString("uniqid").equals(id_fav_remov)) {
//jArrayFavFans.getJSONObject(j).remove(j); //$ I try this to remove element at the current index... But remove doesn't work here ???? $
//int index=jArrayFavFans.getInt(j);
Toast.makeText(getParent(), "Object to remove...!" + id_fav_remov, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
How do I remove a specific element from this JSONArray?
Try this code
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());
}
}
//Remove the element from arraylist
list.remove(position);
//Recreate JSON Array
JSONArray jsArray = new JSONArray(list);
Edit:
Using ArrayList will add "\" to the key and values. So, use JSONArray itself
JSONArray list = new JSONArray();
JSONArray jsonArray = new JSONArray(jsonstring);
int len = jsonArray.length();
if (jsonArray != null) {
for (int i=0;i<len;i++)
{
//Excluding the item at position
if (i != position)
{
list.put(jsonArray.get(i));
}
}
}
In case if someone returns with the same question for Android platform, you cannot use the inbuilt remove() method if you are targeting for Android API-18 or less. The remove() method is added on API level 19. Thus, the best possible thing to do is to extend the JSONArray to create a compatible override for the remove() method.
public class MJSONArray extends JSONArray {
#Override
public Object remove(int index) {
JSONArray output = new JSONArray();
int len = this.length();
for (int i = 0; i < len; i++) {
if (i != index) {
try {
output.put(this.get(i));
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
}
return output;
//return this; If you need the input array in case of a failed attempt to remove an item.
}
}
EDIT
As Daniel pointed out, handling an error silently is bad style. Code improved.
public static JSONArray RemoveJSONArray( JSONArray jarray,int pos) {
JSONArray Njarray=new JSONArray();
try{
for(int i=0;i<jarray.length();i++){
if(i!=pos)
Njarray.put(jarray.get(i));
}
}catch (Exception e){e.printStackTrace();}
return Njarray;
}
JSONArray jArray = new JSONArray();
jArray.remove(position); // For remove JSONArrayElement
Note :- If remove() isn't there in JSONArray then...
API 19 from Android (4.4) actually allows this method.
Call requires API level 19 (current min is 16): org.json.JSONArray#remove
Right Click on Project Go to Properties
Select Android from left site option
And select Project Build Target greater then API 19
Hope it helps you.
i guess you are using Me version, i suggest to add this block of function manually, in your code (JSONArray.java) :
public Object remove(int index) {
Object o = this.opt(index);
this.myArrayList.removeElementAt(index);
return o;
}
In java version they use ArrayList, in ME Version they use Vector.
You can use reflection
A Chinese website provides a relevant solution: http://blog.csdn.net/peihang1354092549/article/details/41957369
If you don't understand Chinese, please try to read it with the translation software.
He provides this code for the old version:
public void JSONArray_remove(int index, JSONArray JSONArrayObject) throws Exception{
if(index < 0)
return;
Field valuesField=JSONArray.class.getDeclaredField("values");
valuesField.setAccessible(true);
List<Object> values=(List<Object>)valuesField.get(JSONArrayObject);
if(index >= values.size())
return;
values.remove(index);
}
In my case I wanted to remove jsonobject with status as non zero value, so what I did is made a function "removeJsonObject" which takes old json and gives required json and called that function inside the constuctor.
public CommonAdapter(Context context, JSONObject json, String type) {
this.context=context;
this.json= removeJsonObject(json);
this.type=type;
Log.d("CA:", "type:"+type);
}
public JSONObject removeJsonObject(JSONObject jo){
JSONArray ja= null;
JSONArray jsonArray= new JSONArray();
JSONObject jsonObject1=new JSONObject();
try {
ja = jo.getJSONArray("data");
} catch (JSONException e) {
e.printStackTrace();
}
for(int i=0; i<ja.length(); i++){
try {
if(Integer.parseInt(ja.getJSONObject(i).getString("status"))==0)
{
jsonArray.put(ja.getJSONObject(i));
Log.d("jsonarray:", jsonArray.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
jsonObject1.put("data",jsonArray);
Log.d("jsonobject1:", jsonObject1.toString());
return jsonObject1;
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
To Remove some element from Listview in android then it will remove your specific element and Bind it to listview.
BookinhHistory_adapter.this.productPojoList.remove(position);
BookinhHistory_adapter.this.notifyDataSetChanged();
We can use iterator to filter out the array entries instead of creating a new Array.
'public static void removeNullsFrom(JSONArray array) throws JSONException {
if (array != null) {
Iterator<Object> iterator = array.iterator();
while (iterator.hasNext()) {
Object o = iterator.next();
if (o == null || o == JSONObject.NULL) {
iterator.remove();
}
}
}
}'
static JSONArray removeFromJsonArray(JSONArray jsonArray, int removeIndex){
JSONArray _return = new JSONArray();
for (int i = 0; i <jsonArray.length(); i++) {
if (i != removeIndex){
try {
_return.put(jsonArray.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return _return;
}

Categories

Resources