I'm trying to use JSONObject's put method in for loop. But I'm not getting Expected output.
Expected output:
{"Result":[{"PostOfficeName":"Bhajan Pura","Pincode":"110096"},{"PostOfficeName":"Gokulpuri","Pincode":"110094"}, and so on...]}
OutPut I'm getting:
{"Result":[{"PostOfficeName":"Bhajan Pura","Pincode":"110096"}]}
here is my code:
try {
JSONObject obj = new JSONObject(loadJsonfromAssets());
JSONArray arr = obj.getJSONArray("Sheet1");
JSONObject finalObj = new JSONObject();
JSONArray ResultArray = new JSONArray();
JSONObject infoObj = new JSONObject();
for (int i=0; i<arr.length();i++){
JSONObject obj1 = arr.getJSONObject(i);
if (obj1.getString("City").equals("New Delhi")){
Log.d("postal", "Found!");
Toast.makeText(this, "" + obj1.getString("Pincode"), Toast.LENGTH_SHORT).show();
infoObj.put("PostOfficeName", obj1.getString("PostOfficeName"));
infoObj.put("Pincode",obj1.getString("Pincode"));
ResultArray.put(infoObj);
}
}
finalObj.put("Result", ResultArray);
System.out.println(finalObj);
} catch (JSONException e) {
e.printStackTrace();
}
Have you tried moving the construction of infoObj inside the loop. By having it outside, you're maintaining state across loop iterations. I suspect you're just updating the same json object each time and adding it to the JSON array. Not sure why you NOT getting duplicates because I do when I run your code.
Change it to this makes it "better"
try {
JSONObject obj = new JSONObject(loadJsonfromAssets());
JSONArray arr = obj.getJSONArray("Sheet1");
JSONObject finalObj = new JSONObject();
JSONArray ResultArray = new JSONArray();
for (int i=0; i<arr.length();i++){
JSONObject obj1 = arr.getJSONObject(i);
if (obj1.getString("City").equals("New Delhi")) {
Log.d("postal", "Found!");
Toast.makeText(this, "" + obj1.getString("Pincode"),
Toast.LENGTH_SHORT).show();
// move instantiation INSIDE loop
JSONObject infoObj = new JSONObject();
infoObj.put("PostOfficeName", obj1.getString("PostOfficeName"));
infoObj.put("Pincode",obj1.getString("Pincode"));
ResultArray.put(infoObj);
}
}
finalObj.put("Result", ResultArray);
System.out.println(finalObj);
} catch (JSONException e) {
e.printStackTrace();
}
Related
im literally new at working with JSON and I have a problem with my Web Service. With normal JSON Objects i no problems. I want to get two Arrays from the Web Service (String and Integer), so i tried to put them into two JSON Array´s and this two into a JSON Object. Now i want them to get into my Android application, but im just getting errors.
public static String constructJSON(Integer[] array, String[] array2) {
JSONObject mainObj = new JSONObject();
try {
JSONObject firstArray = new JSONObject();
firstArray.put("array0", array[0]);
firstArray.put("array1", array[1]);
firstArray.put("array2", array[2]);
firstArray.put("array3", array[3]);
firstArray.put("array4", array[4]);
JSONObject secondArray = new JSONObject();
secondArray.put("sArray0", array2[0]);
secondArray.put("sArray1", array2[1]);
secondArray.put("sArray2", array2[2]);
secondArray.put("sArray3", array2[3]);
secondArray.put("sArray4", array2[4]);
JSONArray JArr = new JSONArray();
JArr.put(firstArray);
JArr.put(secondArray);
mainObj.put("arrays", JArr);
} catch (JSONException e) {
}
return mainObj.toString();
}
And now the method in Android Studio:
private void getBW(String krankheit) {
RequestParams params = new RequestParams();
params.put("krankheit", krankheit);
// Invoke RESTful Web Service with Http parameters
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
try {
// JSON Object
JSONObject obj = new JSONObject(response);
JSONArray firstJsonArr= obj.getJSONArray("array1");
JSONArray secondJsonArr= obj.getJSONArray("array2");
for (int k = 0; k < 5; k++) {
Bewertung1[k] = (Integer) firstJsonArr.get(k);
}
for (int j = 0; j < 5; j++) {
medikament[j] = (String) secondJsonArr.get(j);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
I tried different solution´s, but none of them worked for me. I hope you guys can help me.
I would recommend you to use gson library for android. Its provides simple function to parse from and to json object.
Have a look at this library : https://github.com/google/gson
You switched your function istead of what you wanted it does [{}{}]
Try this:
public static String constructJSON(Integer[] array, String[] array2) {
try {
JSONArray firstArray = new JSONArray ();
firstArray.put( array[0]);
firstArray.put( array[1]);
firstArray.put( array[2]);
firstArray.put( array[3]);
firstArray.put( array[4]);
JSONArray secondArray = new JSONArray ();
secondArray.put(array2[0]);
secondArray.put( array2[1]);
secondArray.put( array2[2]);
secondArray.put( array2[3]);
secondArray.put( array2[4]);
JSONObject JArr = new JSONObject();
JArr.put("firstArr",firstArray);
JArr.put("secondArr", secondArray);
return JArr.toString();
} catch (JSONException e) {
}
return null;
}
this will give you the JSon you wanted , and this is the main code to use it:
JSONObject obj = new JSONObject(response);
JSONArray firstJsonArr= obj.getJSONArray("firstArr");
JSONArray secondJsonArr= obj.getJSONArray("secondArr");
for (int k = 0; k < firstJsonArr.size(); k++) {
Log.e("item "+k,"item data : "+firstJsonArr.get(k));
}
for (int j = 0; j < secondJsonArr.size(); j++) {
Log.e("item "+j,"item data : "+secondJsonArr.get(j));
}
this is good for practices but later you should use a library that does these type of things for you like Gson etc...
The result i want to get:
[
{"id":1,"name":"example1","description":"An example"},
{"id":2, "name":"example2","description":"Just another example"},
... ]
To add new data to JSON i tried this:
String jsonDataString = ALL MY JSON DATA HERE;
JSONObject mainObject = new JSONObject(jsonDataString);
JSONObject valuesObject = new JSONObject();
JSONArray list = new JSONArray();
valuesObject.put("id", "3");
valuesObject.put("name", "example3");
valuesObject.put("description", "Yet another example");
list.put(valuesObject);
mainObject.accumulate("", list);
But i don't get a proper result.
And how to remove a JSON data depend on the value of the ID ?
Thank's.
To build a fresh JSONArray you can use below codes:
try {
JSONArray jsonArray = new JSONArray();
// Object 1
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("id", 1);
jsonObject1.put("name", "example1");
jsonObject1.put("description", "An example");
// Object 2
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("id", 2);
jsonObject2.put("name", "example2");
jsonObject2.put("description", "Just another example");
// Add Object 1 & 2 JSONArray
jsonArray.put(jsonObject1);
jsonArray.put(jsonObject2);
Log.d("JSON", "JSON: " + jsonArray.toString());
} catch (final JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
OUTPUT:
D/JSON: JSON: [{"id":1,"name":"example1","description":"An example"},{"id":2,"name":"example2","description":"Just another example"}]
To add new JSONObject into existing JSONArray you can use below codes:
// Your Existing JSONArray
// [{"id":1,"name":"example1","description":"An example"},
// {"id":2, "name":"example2","description":"Just another example"}]
String jsonDataString = "[{\"id\":1,\"name\":\"example1\",\"description\":\"An example\"},{\"id\":2,\"name\":\"example2\",\"description\":\"Just another example\"}]";
try {
JSONArray jsonArray = new JSONArray(jsonDataString);
// Object 3
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("id", 3);
jsonObject3.put("name", "example3");
jsonObject3.put("description", "Third example");
// Add Object 3 JSONArray
jsonArray.put(jsonObject3);
Log.d("JSON", "JSON: " + jsonArray.toString());
} catch (final JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
OUTPUT:
D/JSON: JSON: [{"id":1,"name":"example1","description":"An example"},{"id":2,"name":"example2","description":"Just another example"},{"id":3,"name":"example3","description":"Third example"}]
To remove JSONObject from JSONArray you can use below codes:
// Your Existing JSONArray
// [{"id":1,"name":"example1","description":"An example"},
// {"id":2,"name":"example2","description":"Just another example"},
// {"id":3,"name":"example3","description":"Third example"}]
String jsonDataString = "[{\"id\":1,\"name\":\"example1\",\"description\":\"An example\"},{\"id\":2,\"name\":\"example2\",\"description\":\"Just another example\"},{\"id\":3,\"name\":\"example3\",\"description\":\"Third example\"}]";
try {
JSONArray jsonArray = new JSONArray(jsonDataString);
Log.d("JSON", "JSON before Remove: " + jsonArray.toString());
// Remove Object id = 2
int removeId = 2;
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
if (object.has("id") && !object.isNull("id")) {
int id = object.getInt("id");
if (id == removeId)
{
jsonArray.remove(i);
break;
}
}
}
Log.d("JSON", "JSON After Remove: " + jsonArray.toString());
} catch (final JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
OUTPUT:
D/JSON: JSON Before Remove: [{"id":1,"name":"example1","description":"An example"},{"id":2,"name":"example2","description":"Just another example"},{"id":3,"name":"example3","description":"Third example"}]
D/JSON: JSON After Remove: [{"id":1,"name":"example1","description":"An example"},{"id":3,"name":"example3","description":"Third example"}]
Hope this will help you.
The root object of the json is an array so you should use a JSONArray, not a JSONObject.
String jsonDataString = ALL MY JSON DATA HERE;
JSONArray mainObject = new JSONArray(jsonDataString);
JSONObject valuesObject = new JSONObject();
valuesObject.put("id", "3");
valuesObject.put("name", "example3");
valuesObject.put("description", "Yet another example");
mainObject.put(valuesObject);
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;
}
}
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());
}
I have a JSONObject:
try {
JSONObject myJsonObject = new JSONObject("{ \"options\": [\"Oui\", \"Non\"] }");
JSONArray myJsonArray = myJsonObject.getJSONArray("options");
} catch (Exception e) {
e.printStackTrace();
}
myJsonArray.toString() contain:
["Yes", "No"]
I need to convert it to a JSONObject like this:
{ "0": "Yes", "1": "No" }
and also to:
{ "Yes": "Yes", "No": "No" }
Any idea how I can do this?
Of course the answer is :
JSONObject myJsonObject = new JSONObject("{ \"options\": [\"Oui\", \"Non\"] }");
JSONArray myJsonArray = myJsonObject.getJSONArray("options");
JSONObject myJsonObject2 = new JSONObject();
for(int i = 0; i < myJsonArray.length(); i++){
String a = myJsonArray.getString(i);
myJsonObject2.put(a, a);
}
Sorry, I got confused.
There is a method toJSONObject for creating new JSONObjects from a JSONArray.
Try this:
try {
JSONObject myJsonObject = new JSONObject("{ \"options\": [\"Oui\", \"Non\"] }");
JSONArray myJsonArray = myJsonObject.getJSONArray("options");
// creates a new JSON Object with the given keys
JSONObject result = myJsonArray.toJSONObject(myJsonArray);
} catch (Exception e) {
e.printStackTrace();
}