How to create a JSONObject for nested json - java

I am unable to create a json object for nested json.
I can create json objects for basic json.
I am unable to add further fields.
final JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", "new name");
jsonObject.put("description", "new election");
} catch (JSONException e) {
e.printStackTrace();
}
Here is my json:
{
"name": "string",
"description": "string",
"candidates": [
"string"
],
"ballotVisibility": "string",
"voterListVisibility": true,
"startingDate": "2019-07-05T20:09:23.311Z",
"endingDate": "2019-07-05T20:09:23.311Z",
"isInvite": true,
"isRealTime": true,
"votingAlgo": "string",
"noVacancies": 0,
"ballot": [
{
"voteBallot": "string",
"voterEmail": "string"
}
]
}

You just need to create a new JSONObject then append it to the parent object with its new name. An example is shown below appending the ballot:
JSONObject jsonObject = new JSONObject();
JSONObject ballot = new JSONObject();
ballot.put("voteBallot","string");
ballot.put("voterEmail","string");
jsonObject.put("name", "new name");
jsonObject.put("description", "new election");
jsonObject.put("ballot", ballot); //Append the other JSONObject to the parent one
System.out.println(jsonObject.toString());
Output(with some formatting):
{
"ballot":
{
"voteBallot":"string",
"voterEmail":"string"
},
"name":"new name",
"description":"new election"
}
You can also use JSONArray instead and append it in the same manner.

Try this:
final JSONObject jsonObject = new JSONObject();
Map<String, String> map = new HashMap<>();
map.put("voteBallot", "string");
map.put("voterEmail", "string");
try {
jsonObject.put("name", "new name");
jsonObject.put("description", "new election");
jsonObject.put("candidates", new String[] {"new String"});
jsonObject.put("ballotVisibility", "string");
jsonObject.put("voterListVisibility", true);
jsonObject.put("startingDate", LocalDateTime.now().atZone(ZoneOffset.UTC));
jsonObject.put("ballot", new Map[]{map});
System.out.println("jsonObject = " + jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
it's not all the fields but it's all the different types hope it helps.
Output:
{
"ballot":[
{
"voteBallot":"string",
"voterEmail":"string"
}
],
"candidates":[
"new String"
],
"ballotVisibility":"string",
"name":"new name",
"voterListVisibility":true,
"description":"new election",
"startingDate":"2019-07-05T22:34:58.750Z"
}

Related

how to remove json object from json Array using org.json.simple

I have a JSON file which is an JSON ARRAY with some JSON Objects and I want to remove the entire json Object if the value of longitude or latitude is an empty string "".
I am using the library org.json.simple. Here is my json file:
[ { "Longitude": 9.96233,
"Latitude": 49.80404 },
{
"Longitude": 6.11499,
"Latitude": 50.76891
},
{ "Longitude": 6.80592,
"Latitude": 51.53548
},
{
"Longitude": 9.50523,
"Latitude": 51.31991 },
{
"Longitude": ""
"Latitude": ""
},
{
"Longitude": 9.93368,
"Latitude": ""
},
{
"Longitude": 11.56122,
"Latitude": 48.14496
},
{
"Longitude": 13.34253,
"Latitude": 52.5319
},
{
"Longitude": 6.11327,
"Latitude": 50.77715
},
{
"Longitude": ""
"Latitude": ""
}
]
and here's where I am stuck. :
JSONParser jsonParser = new JSONParser();
try (FileReader reader = new FileReader ("output.json")) {
Object obj = jsonParser.parse(reader);
JSONArray list = (JSONArray) obj;
list.forEach(node -> {
String vari = (String)((JSONObject)node).get("longitude").toString();
if (vari==null) {
((JSONObject) node).remove();
System.out.println("deleted");
}
}
...
Any suggestions how can I change my code ?
You need to remove the node from the list but because of concurrent modification problem (modifying the list you are looping) you need another list.
I think it is easiest to collect into the new list all the nodes that qualify so like:
#SuppressWarnings("unchecked")
#Test
public void test() throws Exception {
JSONParser jsonParser = new JSONParser();
JSONArray listNonNull = new JSONArray();
try (FileReader reader = new FileReader("output.json")) {
JSONArray list = (JSONArray) jsonParser.parse(reader);
((Collection<JSONObject>)list).forEach(node -> {
// here any check that qualifies the node like also checking "Latitude"
// Also no need to cast to a String
Object vari = node.get("Longitude");
if (vari != null && !vari.equals("")) {
listNonNull.add(node);
}
});
} catch (Exception e) {
throw e;
}
}
If you wish to use only the original list you can collect items to be removed to an another list and use it to remove nodes from the original list:
public void test2() throws Exception {
JSONParser jsonParser = new JSONParser();
JSONArray toBeRemoved = new JSONArray();
try (FileReader reader = new FileReader("output.json")) {
JSONArray list = (JSONArray) jsonParser.parse(reader);
((Collection<JSONObject>) list).forEach(node -> {
Object vari = node.get("Longitude");
// here any check that qualifies the node like also checking "Latitude"
if (vari != null && !vari.equals("")) {
return; // not to be removed
}
toBeRemoved.add(node);
});
list.removeAll(toBeRemoved);
} catch (Exception e) {
throw e;
}
}
use .remove instead of .clear in the code.
JSONParser jsonParser = new JSONParser();
try (FileReader reader = new FileReader("output.json")) {
Object obj = jsonParser.parse(reader);
JSONArray list = (JSONArray) obj;
ArrayList<JSONObject> objList = (ArrayList<JSONObject>) list.stream().filter(node -> {
String longitude = ((JSONObject) node).get("Longitude").toString();
String latitude = ((JSONObject) node).get("Latitude").toString();
if (longitude.isEmpty() || latitude.isEmpty()) {
return false;
}
return true;
}).collect(Collectors.toList());
} catch (IOException | ParseException e) {
e.printStackTrace();
}

Writing to a JSON file

I am working on an android application using a json file in order to store data used by the application.
I have a Json file in the asset folder, including one object "plants".
In the Dashboard.java file, I would like to add an object to the json file.
I tried this by using the put() function, but I doesnt seem to write in the actual file.
Dashboard.java :
String name = intent.getStringExtra(AddAPlant.EXTRA_TEXT1);
String description = intent.getStringExtra(AddAPlant.EXTRA_TEXT2);
String url = intent.getStringExtra(AddAPlant.EXTRA_TEXT3);
JSONObject jsonObj= new JSONObject();
try {
jsonObj.put("name", name);
jsonObj.put("description", description);
jsonObj.put("cameralink", url);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
plantArray = new JSONArray();
plantArray.put(jsonObj);
Json file located in asset folder :
{
"plants": [
{
"name": "Pepper",
"decription": "This is a big plant",
"CameraLink": "https://messir.uni.lu/bicslab/blab-cam1-snapshots/gallery-images/latest.png"
},
{
"name": "Tomatoe",
"decription": "This is a big plant",
"CameraLink": "https://messir.uni.lu/bicslab/blab-cam2-snapshots/gallery-images/latest.png"
},
{
"name": "Small Tomato",
"decription": "It needs a lot of water",
"CameraLink": "https://messir.uni.lu/bicslab/blab-cam3-snapshots/gallery-images/latest.png"
}
]
}
Desired output :
{
"plants": [
{
"name": "Pepper",
"decription": "This is a big plant",
"CameraLink": "https://messir.uni.lu/bicslab/blab-cam1-snapshots/gallery-images/latest.png"
},
{
"name": "Tomatoe",
"decription": "This is a big plant",
"CameraLink": "https://messir.uni.lu/bicslab/blab-cam2-snapshots/gallery-images/latest.png"
},
{
"name": "Small Tomato",
"decription": "It needs a lot of water",
"CameraLink": "https://messir.uni.lu/bicslab/blab-cam3-snapshots/gallery-images/latest.png"
},
{
"name": name,
"decription": description,
"CameraLink": url
]
}
i do not think it is possible to write to /assets at run time check this answer
try using app specific files docs
To make changes to JSON. Read from file (String data) and initialize a JSONobject.
JSONObject obj = new JSONObject("string from your file")
JSONObject jsonObject = new JSONObject("data from file");
JSONArray jsonArray = jsonObject.getJSONArray("plants");
JSONObject jsonObj = new JSONObject();
jsonObj.put("name", name);
jsonObj.put("description", description);
jsonObj.put("cameralink", url);
jsonArray = jsonArray.put(jsonObj);
jsonObject = jsonObject.put("plants", jsonArray);
//convert json object to string
String data = jsonObject.toString();
FileOutputStream fout = context.openFileOutput(filename, Context.MODE_PRIVATE);
fout.write(data.getBytes());

Giving Name (Heading) to Objects in JsonArray

I want to send following data to server. It contains JsonArray of JsonObjects as shown below.
{
"users":[
{"user-1":{
"Name":"Amit",
"Age":"32",
"Gender":"male",
"Hobby":"Cricket"
}
"user-2":{
"Name":"Subodh",
"Age":"30",
"Gender":"male",
"Hobby":"Chess"
}
"user-3":{
"Name":"Mala",
"Age":"27",
"Gender":"female",
"Hobby":"Singing"
}
}
]
}
This is how I wrote json code for the same.
JSONObject userObject = new JSONObject();
JSONArray userArray = new JSONArray();
JSONObject user1 = new JSONObject();
try {
user1.put("Name", "Amit");
user1.put("Age", "32");
user1.put("Gender", "Male");
user1.put("Hobby", "Cricket");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject user2 = new JSONObject();
try {
user2.put("Name", "Subodh");
user2.put("Age", "30");
user2.put("Gender", "Male");
user2.put("Hobby", "Chess");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject user3 = new JSONObject();
try {
user3.put("Name", "Mala");
user3.put("Age", "27");
user3.put("Gender", "Female");
user3.put("Hobby", "Singing");
} catch (JSONException e) {
e.printStackTrace();
}
userArray.put(user1);
userArray.put(user2);
userArray.put(user3);
try {
userObject.put("user", userArray);
} catch (JSONException e) {
e.printStackTrace();
}
However I am not able to figure out how to give name to Objects (user-1, user-2 etc.) in the JsonArray. Can someone help to do that. I want to give Heading to each JsonObject in the JsonArray.
Your JSON is invalid.
Elements in JSON arrays don't have keys ("headings", as you call them). Only values in JSON objects have keys.
So, this is wrong:
{
"users": [
"user-1": {
"Name": "Amit",
"Age": "32",
"Gender": "male",
"Hobby": "Cricket"
}
]
}
While this is correct:
{
"users": {
"user-1": {
"Name": "Amit",
"Age": "32",
"Gender": "male",
"Hobby": "Cricket"
}
}
}
To get the correct JSON, simply use a JSONObject instead of a JSONArray:
JSONObject resultObject = new JSONObject();
JSONObject usersObject = new JSONObject();
JSONObject user1 = new JSONObject();
user1.put("Name", "Amit");
user1.put("Age", "32");
user1.put("Gender", "Male");
user1.put("Hobby", "Cricket");
usersObject.put("user-1", user1);
// repeat for user 2, 3, 4, ...
resultObject.put("users", usersObject);
Write the JSON object name like below code in every JSONObject creation :-
JSONObject jsonobj = new JSONObject("user1 ");
try {
jsonobj.put("Name", "Amit");
jsonobj.put("Age", "32");
jsonobj.put("Gender", "Male");
jsonobj.put("Hobby", "Cricket");
} catch (JSONException e) {
e.printStackTrace();
}

How to write JSON object in java code?

My Json are following
{
"q": {
"region": "NYC",
"or": [
{
"duration": "12"
}
]
},
"sort": "recent"
}
How to write in JsonObject.I tried with following code:
JSONObject obj = new JSONObject();
JSONObject obj1 = new JSONObject();
JSONObject obj2 = new JSONObject();
JSONObject obj4 = new JSONObject();
try {
obj.put("q", obj1);
obj.put("sort", "recent");
obj1.put("reg", "NYC");
obj2.put("duration", new Integer(12));
obj4.put()
} catch (JSONException e) {
}
I got stuck in creating Array of list. How can I convert into Json Object?
You may build the JSONObject in this way:
public class Test {
public static void main(String[] args) {
JSONObject obj = new JSONObject();
obj.put("q", new JSONObject()
.put("region", "NYC")
.put("or", new JSONArray()
.put(new JSONObject()
.put("duration","12"))))
.put("sort", "recent");
System.out.println(obj);
}
}
The output:
{"q":{"or":[{"duration":"12"}],"region":"NYC"},"sort":"recent"}

Android : Json Parsing show error

[
{
"description": "My home",
"name": "Sweet Home",
"point": {
"lat": 22.890976,
"long": 90.459097
},
"type": 1,
"cid": "5319197376176516414"
}
This is my json file for parsing information. Here is my code for parsing name and lng.
BufferedReader jsonReader = new BufferedReader(new InputStreamReader(this.getResources().openRawResource(R.raw.map)));
StringBuilder jsonBuilder = new StringBuilder();
try {
for (String line = null; (line = jsonReader.readLine()) != null;) {
jsonBuilder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(jsonBuilder.toString());
JSONArray jsonArray = new JSONArray(tokener);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String title = jsonObject.getString("name");
String lhg = jsonObject.getJSONObject("point").getString("lng");
} catch (FileNotFoundException e) {
Log.e("jsonFile", "file not found");
} catch (IOException e) {
Log.e("jsonFile", "ioerror");
} catch (JSONException e) {
Log.e("jsonFile", "error while parsing json");
}
}
}
It show's me an exception error while parsing json. How do i solve that? What was my problem?
Because "Point" in your JSON object never contains a property called "lng"
String lhg = jsonObject.getJSONObject("point").getString("lng")
it does contain one named "long"
"point": {
"lat": 22.890976,
"long": 90.459097
},
So the code to fetch the longitude should look like this:
String lhg = jsonObject.getJSONObject("point").getString("long")
String lhg = jsonObject.getJSONObject("point").getString("lng") use "long" instead of lng.

Categories

Resources