Append or remove data from JSON - java

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

Related

Using "put" method of JSONObject in for loop (java)

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

Having trouble finding the right JSON path for android project

JSONObject baseJsonResponse = new JSONObject(newsJSON);
JSONObject responseObj = baseJsonResponse.getJSONObject("response");
JSONArray resultArray = responseObj.getJSONArray("results");
for (int i =0;i<resultArray.length();i++){
String sectionName = resultArray.getString("sectionName");}
I want to get the section name for this url:
https://content.guardianapis.com/search?api-key=e11b8d10-d6ef-4fb7-9c12-094c58d37687
You can get Json Value Like this.
JSONObject baseJsonResponse = new JSONObject(newsJSON);
JSONObject responseObj = null;
try {
responseObj = baseJsonResponse.getJSONObject("response");
JSONArray resultArray = responseObj.getJSONArray("results");
int size = resultArray.length();
for (int i =0;i<size;i++){
JSONObject myJson = resultArray.getJSONObject(i);
String sectionName = myJson.getString("sectionName");
}
} catch (JSONException e) {
e.printStackTrace();
}

Get Key and values from JSONObject

I am trying to extract Key and values from my JSONObject. But i am not able to do that. Here is the JSON:
[{"id":["5"]},{"Tech":["Java"]}]
It is a String initially. I have converted that to JSONObject using :
JSONObject jsonObj = new JSONObject("[{"id":["5"]},{"Tech":["Java"]}]");
Then i am trying to get the key and value by:
jsonObj.getString("id");
But its giving me null. Can anyone help me out here?
Try this:
try {
JSONArray jsonArr = new JSONArray("[{\"id\":[\"5\"]},{\"Tech\":[\"Java\"]}]");
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
String k = jsonObj.keys().next();
Log.i("Info", "Key: " + k + ", value: " + jsonObj.getString(k));
}
} catch (JSONException ex) {
ex.printStackTrace();
}
Parameter you are sending is JsonArray and referring to JsonObject. The Correct way is
JSONObject jsonObj = new JSONObject("{'id':['5','6']},{'Tech':['Java']}");
System.out.println(jsonObj.getString("id"));
JSONArray jsonArray = new JSONArray("[{'id':['5','6','7','8']},{'Tech':['Java']}]");
System.out.println(jsonArray.length());
for(int i=0;i<jsonArray.length();i++){
System.out.println(jsonArray.getJSONObject(i).getString("id"));
}
Because at id you dont have a string , you have a array of string ,
so insted of doing this
jsonObj.getString("id");
do this
jsonObj.getArray("id"); this will give you that array in return
like if you have a Json Array at id then you have to do this
jsonObj.getJSONArray("id");

Android (Java) convert JSONArray to JSONObject

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

Using Java to decode JSON array of objects

I have JSON as follows:
[{"0":"1","id":"1","1":"abc","name":"abc"},{"0":"2","id":"2","1":"xyz","name":"xyz"}]
It is an array of objects.
I need to parse it using Java. I am using the library at :
http://code.google.com/p/json-simple/downloads/list
Example 1 at this link approximates what I require:
http://code.google.com/p/json-simple/wiki/DecodingExamples
I have the following code:
/** Decode JSON */
// Assuming the JSON string is stored in jsonResult (String)
Object obj = JSONValue.parse(jsonResult);
JSONArray array = (JSONArray)obj;
JSONObject jsonObj = null;
for (int i=0;i<array.length();i++){
try {
jsonObj = (JSONObject) array.get(i);
} catch (JSONException e) {
e.printStackTrace();
}
try {
Log.d(TAG,"Object no." + (i+1) + " field1: " + jsonObj.get("0") + " field2: " + jsonObj.get("1"));
} catch (JSONException e) {
e.printStackTrace();
}
}
I am getting the following exception:
java.lang.ClassCastException: org.json.simple.JSONArray
// at JSONArray array = (JSONArray)obj;
Can someone please help?
Thanks.
Instead of casting your Object to JSONArray, you should do it like this:
JSONArray mJsonArray = new JSONArray(jsonString);
JSONObject mJsonObject = new JSONObject();
for (int i = 0; i < mJsonArray.length(); i++) {
mJsonObject = mJsonArray.getJSONObject(i);
mJsonObject.getString("0");
mJsonObject.getString("id");
mJsonObject.getString("1");
mJsonObject.getString("name");
}

Categories

Resources