JSONArray equivalent to JSONObject's .has() method? - java

I've been using this:
JSONObject json = new JSONObject(output);
if (json.has("errors"))
{
}
Now I have a JSONArray... how do I check for it having a child called "errors"?

Try this:
JSONArray array;
for(int i = 0; i < array.length(); i++){
JSONObject json = array.getJSONObject(i);
if (json.has("errors")){
//magic
}
}

Use a try catch block like this :
boolean arrayexists = true;
try{
json.has("errors") }
catch(Exception e){
arrayexists = false;}
if (arrayexists) {
//majic
}

Related

Parse json in Java android studio

I have this code to parse a json in Java, but problem is my json looks like this
{"ime":"Alen","prezime":"Osmanagi\u0107","test":[1,2,3,4,5],"test2":{"1":"test","2":"555","test":"888","om":"hasd"}}
And my java code for parsing looks like :
protected void onPostExecute(String result) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListView listView =(ListView)findViewById(R.id.jsonList);
if ( true) {
try {
JSONArray mojNiz = response.getJSONArray("");
List<JSON> noviJSON = new ArrayList<>();
//Popuniti podacima
for (int i = 0; i < mojNiz.length(); i++) {
JSON jsonObj = new JSON();
JSONObject mojObj = mojNiz.getJSONObject(i);
jsonObj.setIme(mojObj.getString(KEY_NAME));
// jsonObj.setPrezime(mojObj.getString(KEY_DOB));
//jsonObj.setPrezime(mojObj.getString(KEY_DESIGNATION));
noviJSON.add(jsonObj);
}
adapter = new Adapter(noviJSON, getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this,
"Problem u loadiranjuz podataka",
Toast.LENGTH_LONG).show();
}
How can I parse this particular json string ???
First get the JSONObject and then the array inside it
JSONObject jsonObject = new JSONObject(jsonString);
String objectIme = jsonObject.getString("ime");
String prezime = jsonObject.getString("prezime");
The above line will get the whole object and from this object you can get other objects and the array test1 and test2 like below then you can loop through that array like you did
JSONArray jArray1 = new JSONArray(jsonObject.getJSONArray("test1"));
JSONArray jArray2 = new JSONArray(jsonObject.getJSONArray("test2"));
for (int i = 0; i < jArray1 .length(); i++) {
JSON jsonObj = new JSON();
JSONObject mojObj = jArray1.getJSONObject(i);
jsonObj.setIme(mojObj.getString(KEY_NAME));
}
You are parsing your json wrong. Your json starts with jsonObject instead of jsonArray. So in your case you have to start like this
(assuming that your result variable of onPostExecute method has the json string)
JSONObject mojNiz = new JSONObject(result);
Now from the above mojNiz object you can get your json array
String s = "{\"ime\":\"Alen\",\"prezime\":\"Osmanagi\\u0107\",\"test\":[1,2,3,4,5],\"test2\":{\"1\":\"test\",\"2\":\"555\",\"test\":\"888\",\"om\":\"hasd\"}}";
try {
JSONObject jsonObject = new JSONObject(s);
jsonObject.getString("ime");
jsonObject.getString("prezime");
JSONArray jsonArray = jsonObject.getJSONArray("test");
List<Integer> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
list.add((Integer) jsonArray.get(i));
}
JSONObject testObject = jsonObject.getJSONObject("test2");
testObject.getString("1");
testObject.getString("2");
} catch (JSONException e) {
e.printStackTrace();
}

ArrayList of Strings to JSON

I have an ArrayList that contains values as follows
"One"
"Two"
"Three" etc.
I am trying to generate an JSON Object / Array out of this. My code is below:
peopleNames = personAdapter.getArrayListNames();
peoplePhones= personAdapter.getArrayListPhones();
JSONNames = new JSONObject();
JSONPhones = new JSONObject();
for (int i = 0; i < peopleNames.size(); i++){
try {
System.out.println(peopleNames.get(i));
JSONNames.put("Name",peopleNames.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
for (int i = 0; i < peoplePhones.size(); i++){
try {
JSONPhones.put("Phone",peoplePhones.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
jsonArrayNames = new JSONArray();
System.out.println(jsonArrayNames.toString());
However my output is just:
[{"Name":"One"}]
Why don't you merge the data ? I think, from your adapter, you're able to get people directly, right ? If so, I propose you the following :
people = personAdapter.getPersons();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < people.size(); i++) {
JSONObject object = new JSONObject();
object.put("Name", people.name());
object.put("Phone", people.phone());
jsonArray.put(object);
}
The resulted JSON will be :
[
{"Name":"One",
"Phone": "OnePhone"},
{"Name":"Two",
"Phone": "TwoPhone"},
]

Java - ArrayIndexOutofBoundsException when trying to populate arrays by iterating over a JSONArray [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
I am trying to populate the server and the itemsId by iterating over a JSONArray.
String jsonString = '"[{\"label\":\"Label 1\",\"srvid\":1},{\"label\":\"label 2\",\"srvid\":2}]"';
String[] servers = new String[100];
Integer itemsId[] = new Integer[100];
try {
JSONArray array = new JSONArray(jsonString);
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
servers[i] = o.getString("label");
itemsId[i] = o.getInt("srvid");
}
} catch (JSONException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
However, I am getting ArrayIndexOutOfBoundsException here but I don't know how to further solve this. I wonder what could be wrong in the declaration of the arrays and how they are populated.
The only problem I can see here is the single quotes that are enclosing the JSON string. Other than that, the code works flawlessly in Intellij IDEA 2018.1.3.
String jsonString = "[{\"label\":\"Label 1\",\"srvid\":1},{\"label\":\"label 2\",\"srvid\":2}]";
String[] servers = new String[100];
Integer itemsId[] = new Integer[100];
try {
JSONArray array = new JSONArray(jsonString);
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
servers[i] = o.getString("label");
itemsId[i] = o.getInt("srvid");
}
System.out.println(Arrays.toString(servers)); //Added for testing purposes
System.out.println(Arrays.toString(itemsId)); //Added for testing purposes
} catch (JSONException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
The two System.out.println(Arrays.toString(arr)) calls gives the expected output. No problems.
I Executed the following code which is a replica of yours (changed the jsonString).
String jsonString = "[{'label':'Label 1','srvid':1},{'label':'label 2','srvid':2}]";
String[] servers = new String[100];
Integer itemsId[] = new Integer[100];
try {
JSONArray array = new JSONArray(jsonString);
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
servers[i] = o.getString("label");
System.out.println(servers[i]);
itemsId[i] = o.getInt("srvid");
System.out.println(itemsId[i]);
}
} catch (JSONException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
And got the response.
Label 1
1
label 2
2
So code looks good, if there is nothing wrong with JSON String.
So what I did is I have initialized the length of the arrays by the size of the JSONArray. And taken them inside the try catch.
try {
JSONArray array = new JSONArray(jsonString);
String[] servers = new String[array.length()];
Integer[] itemsId = new Integer[array.length()];
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
servers[i] = o.getString("label");
itemsId[i] = o.getInt("srvid");
}
//REST OF THE CODES
} catch (JSONException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}

android JSONException index 1 out of range [0..1] (Parse 2 json arrays inside 1 loop)

I have code like this, the value of jArrAnswer is
[{"answer":"Yes"},{"answer":"No"},{"answer":"maybe"},{"answer":"yrg"}]
the result from jArrAnswer.length() is 4
but why I got error
org.json.JSONException: Index 1 out of range [0..1).
try {
JSONArray jArrAnswerid = new JSONArray(answerid);
JSONArray jArrAnswer = new JSONArray(answer);
for (int i = 0; i < jArrAnswer.length(); i++) {
JSONObject jObjAnswerid = jArrAnswerid.getJSONObject(i);
JSONObject jObjAnswer = jArrAnswer.getJSONObject(i);
String ansid = jObjAnswerid.getString("answerid");
String ans= jObjAnswer.getString("answer");
GroupModel item2 = new GroupModel(String.valueOf(i + 1), ans, ansid);
}
} catch (Exception e) {
Log.w("asdf", e.toString());
}
You are iterating the for loop over jArrAnswer while your fetching the index i over jArrAnswerid.
Check and make sure that the jArrAnswerid.size() is equal to the jArrAnswer.size().
Print the jArrAnswerid.size() and check.
Try this
try {
JSONArray jArrAnswer = new JSONArray(answer);
for (int i = 0; i < jArrAnswer.length(); i++) {
JSONObject jObjAnswer = jArrAnswer.getJSONObject(i);
String ansid = jObjAnswer.getString("answerid");
String ans= jObjAnswer.getString("answer");
}
} catch (Exception e) {
Log.w("asdf", e.toString());
}
provided "answer" is your json array response
Try
String json = "[{\"answer\":\"Yes\",\"answerid\":\"1\"},{\"answer\":\"No\",\"answerid\":\"2\"},{\"answer\":\"maybe\",\"answerid\":\"3\"},{\"answer\":\"yrg\",\"answerid\":\"4\"}]";
try {
JSONArray jsonArray = new JSONArray(json);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String answerId = jsonObject.getString("answerid");
String answer = jsonObject.getString("answer");
//Use answerId and answer
}
}
} catch(JSONException e) {
e.printStackTrace();
}

Android Arraylist to JSONObject

Im trying to take the values from the ArrayList and put in to an JSONObject. I have written the below code but it does only put the last value from arraylist to jsonobject
I am trying to achieve this out put.
{"lstContacts":"array_value"},{"lstContacts":"array_value"},{"lstContacts":"array_value"}
This is my code
ArrayList<String> tokens;
JSONObject contactsObj;
..
...
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
for (int i = 0; i < tokens.size(); i++) {
contactsObj.put("ContactToken", tokens.get(i));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String jsonStr = contactsObj.toString();
Log.e("CONTACTS", jsonStr); // adds only last array to json object
}
});
Try this:
JSONObject contactsObj = new JSONObject();
JSONArray contactsArray = new JSONArray();
try {
for (int i = 0; i < tokens.size(); i++) {
JSONObject contact = new JSONObject();
contact.put("ContactToken", tokens.get(i));
contactsArray.put(i, contact);
}
contactsObj.put("contacts", contactsArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String jsonStr = contactsObj.toString();
Log.e("CONTACTS", jsonStr); // adds only last array to json object
The result jsonStr will look like this:
{
"contacts":[
{
"ContactToken":"someToken"
},
{
"ContactToken":"someToken"
},
{
"ContactToken":"someToken"
},
{
"ContactToken":"someToken"
}
]
}
You are overriding the object because u are using an JsonObject for an ArrayList, the solution is to use an JsonArray contactObj in your case
JSONArray contactsObj;
for (int i = 0; i < tokens.size(); i++) {
contactsObj.put(i, tokens.get(i));
}
JSONObject contactsObj = new JSONObject();
for (int i = 0; i < tokens.size(); i++) {
contactsObj.put("lstContacts" + String.valueOf(i), tokens.get(i));
}
// done...
contactsObj.put("ContactTokens", new JSONArray(tokens));
Is probably closest to what you're looking for. You don't even need to loop for this.
This will give you the object
{
"ContactTokens":["token1","token2","token3"...]
}

Categories