Android, cannot iterate through JSONArray inside for-loop - java

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

Related

Java jsonObject.get() returns null or an empty object for specific key [duplicate]

This question already has answers here:
Json object returning null against given key
(3 answers)
Closed 5 years ago.
Here's the JSON response.
The following works:
jsonObject.get("title").getAsString();
jsonObject.get("author").getAsJsonObject().get("profile_photo").getAsString();
but jsonObject.get("primary_photo").getAsString() (from line 60) returns an Unsupported Exception: null error. I've tried replacing getAsString() with toString() but the latter returns an empty string.
Try this
Use optJSONObject and optString in your code . And the root is [],so you should use JSONArray
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
// use optJSONObject
JSONObject author = jsonArray.optJSONObject(i).optJSONObject("author");
// use optString , it did not return null
String profile_photo = author.optString("profile_photo");
String primary_photo = jsonArray.optJSONObject(i).optString("primary_photo");
}
} catch (JSONException e) {
e.printStackTrace();
}
Gson
JsonArray jsonElements = new JsonParser().parse(response).getAsJsonArray();
for (int i = 0; i < jsonElements.size(); i++) {
JsonObject jObject = jsonElements.get(i).getAsJsonObject();
// edited here
String primary_photo = jObject.get("primary_photo").getAsString();
JsonObject author = jObject.getAsJsonObject("author");
String profile_photo = author.get("profile_photo").getAsString();
}
I think the Problem is, that your JSON response contains an Array. You have to create an JSONArray from the response-string and than iterate about it to get your values. Or if this array always contains one object:
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
Try this,
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject author = jsonArray.get(i).getJSONObject"author");
String profile_photo = author.getString("author");
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this:
try {
JSONArray jarr=new JSONArray(response); // response is whole json response
for (int i=0;i<jarr.length();i++){
JSONObject jobj=jarr.getJSONObject(i);
String primary_photo=jobj.getString("primary_photo");
}
} catch (JSONException e) {
e.printStackTrace();
}

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

Trouble extracting values from JSON object in Java

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

Convert JSONObject to List<JSONObject> or a String to List<JSONObject>

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

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