Android Arraylist to JSONObject - java

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

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

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

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

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
}

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