ArrayList of Strings to JSON - java

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"},
]

Related

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"...]
}

Converting array list object to jsonarray

I have arraylist that needs to be converted to json array to post in the server
the format of json should be like this:
{
p:1,
s:["a":1,"b":2],["a":2,"b":3],["a":3,"b":4]
}
Let say I have:
List<MyObject> objectList = new ArrayList<MyObject>();
MyObject myObject = new MyObject();
myObject .setA(1);
myObject .setB(2);
myObject .setA(2);
myObject .setB(3);
myObject .setA(3);
myObject .setB(4);
objectList.add(myObject);
My current code is:
for (int i = 0; i < objectList.size(); i++) {
JSONArray ar = new JSONArray();
ar.put("a:"+objectList.get(i).getA());
ar.put("b:"+objectList.get(i).getB());
jOuter.put("s",ar);
}
but this doesnt work, the current return is:
{"p":1,"s":["a:20","b:10.0"]}
Thanks.
Shouldn't it be something like this?
JSONArray ar = new JSONArray();
for (int i = 0; i < objectList.size(); i++) {
JSONObject objects = new JSONObject();
objects.put("a", objectlist.get(i).getA();
objects.put("b", objectlist.get(i).getB();
ar.put(objects);
}
jOuter.put("s",ar);
Your s entry is actually a JsonArray, while your p is just a property. Here I am using Gson but you could easily apply it to whichever library you are using. So you can do the following:
JsonObject jObj = new JsonObject();
jObj.addProperty("p", 1);
JsonArray sArr = new JsonArray();
for (int i = 0; i < objectList.size(); i++)
{
JsonObject innerObj = new JsonObject();
innerObj.addProperty("a:"+objectList.get(i).getA());
innerObj.addProperty("b:"+objectList.get(i).getB());
sArr.add(innerObj);
}
jObj.addProperty("s", sArr);
The output is:
{
"p":1,
"s":[{"a":1,"b":2},{"a":3,"b":4}]
}
Your required format is invalid.
I think you are looking for something like this
{
"p": 1,
"s": [
{
"a": 1,
"b": 2
},
{
"a": 2,
"b": 3
},
{
"a": 3,
"b": 4
}
]
}
For this code will be like as below
JSONArray jArray = new JSONArray();
for (int i = 0; i < objectList.size(); i++) {
JSONObject job= new JSONObject();
job.put("a",objectList.get(i).getA());
job.put("b",objectList.get(i).getB());
jArray .put(job);
}
try {
jOuter.put("s", jArray );
} catch (JSONException e) {
e.printStackTrace();
}
Please check following code: This will make the proper formatting:
JSONObject jo = new JSONObject();
try {
jo.put("p", "1");
JSONArray jarr = new JSONArray();
for (MyObject listItem : objectList) {
JSONObject inner = new JSONObject();
inner.put("a", listItem.getA());
inner.put("b", listItem.getB());
jarr.put(inner);
}
jo.put("s", jarr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It will return output like:
{
"p":1,
"s":[{"a":1,"b":2},{"a":2,"b":3},{"a":3,"b":4}]
}
This makes a proper json, which I think you need! Do let me know, if I am wrong somewhere.

Java Android - How to sort a JSONArray based on keys

I'm getting this string (from a webservice) into a JSONArray like this,
[
{
"lat": "-16.408545",
"lon": "-71.539105",
"type": "0",
"distance": "0.54"
},
{
"lat": "-16.4244317845",
"lon": "-71.52562186",
"type": "1",
"distance": "1.87"
},
{
"lat": "-16.4244317845",
"lon": "-71.52562186",
"type": "1",
"distance": "0.22"
}
]
I need to sort it by the distance key to show the nearest first and farthest last. I didn't try any code because I really don't have any ideas. I'm not using the GSON library, I'm using org.json.JSONArray.
First parse your array in a list
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonList = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonList.add(jsonArray.getJSONObject(i));
}
then use collection.sort to sort the newly created list
Collections.sort( jsonList, new Comparator<JSONObject>() {
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get("distance");
valB = (String) b.get("distance");
}
catch (JSONException e) {
//do something
}
return valA.compareTo(valB);
}
});
Insert the sorted values in your array
for (int i = 0; i < jsonArray.length(); i++) {
sortedJsonArray.put(jsonList.get(i));
}
Parse your json object into a model say array-List and sort it using comparator.
ArrayList<ClassObject> dataList = new ArrayList<String>();
JSONArray array = new JSONArray(json);
for(Object obj : jsonArray){
dataList.add(//your data model);
}
Please refer this link for sorting of array-list
http://java2novice.com/java-collections-and-util/arraylist/sort-comparator/
Try this. It should work
ArrayList<JSONObject> array = new ArrayList<JSONObject>();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
try {
array.add(jsonArray.getJSONObject(i));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Collections.sort(array, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject lhs, JSONObject rhs) {
// TODO Auto-generated method stub
try {
return (lhs.getDouble("distance").compareTo(rhs.getDouble("distance")));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}
}
});
And after this you can convert sorted ArrayList array into JSONArray.
JSONArray jsonArray = new JSONArray(array);
String jsonArrayStr = jsonArray.toString();
In kotlin you can do as below
Parse your array in a list
val sortedJsonArray = JSONArray()
val jsonList = ArrayList<JSONObject>()
for (i in 0 until jsonArray.length()) {
jsonList.add(jsonArray.getJSONObject(i))
}
Sort the newly created list
jsonList.sortWith { a, b ->
var valA = String()
var valB = String()
try {
valA = a.get("distance") as String
valB = b.get("distance") as String
} catch (e: JSONException) {
e.printStackTrace()
}
valA.compareTo(valB)
}
Insert the sorted values in your json array
for (i in 0 until jsonArray.length()) {
sortedJsonArray.put(jsonList[i])
}
Thanks to #crysis for his answer.

Categories