How to add subnode to json file using json-simple - java

I create json file with the folloing code:
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONObject;
public class CreatingJSONDocument {
public static void main(String args[]) {
//Creating a JSONObject object
JSONObject jsonObject = new JSONObject();
//Inserting key-value pairs into the json object
jsonObject.put("ID", "1");
jsonObject.put("First_Name", "Shikhar");
try {
FileWriter file = new FileWriter("E:/output.json");
file.write(jsonObject.toJSONString());
file.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("JSON file created: "+jsonObject);
}
}
OUTPUT:
JSON file created: {
"First_Name":"Shikhar",
"ID":"1"}
How can I add content of java map to the this json output as a new node sothat I have at the end the following output:
JSON file created: {
"First_Name":"Shikhar",
"ID":"1",
"data": {
"a": "Test1",
"b": "Test2"
}
}

You just need to add another object of type JsonObject and it will do that
//...
jsonObject.put("ID", "1");
jsonObject.put("First_Name", "Shikhar");
jsonObject.put("data", new JSONObject(data));
//...
And that will return the output what you want
In case you need add more fields without a object a good practice its do the next:
JSONObject mainFields = new JSONObject();
mainFields.put("id", "1");
JSONObject secondFields = new JSONObject();
secondFields.put("field1", "some cool");
secondFields.put("field2", "not cool");
mainFields.put("data", secondFields);
This return:
{
"id":"1",
"data":{
"field1": "some cool",
"field2": "not cool"
}
}

Related

How to save data from textfields to json file?

how to save data from our textfields. For example i want to get this:
[
{
"Patient": {
"name": "John",
"surname": "Cena"
}
},
{
"Patient2": {
"name": "Roger",
"surname": "Federer"
}
}
]
And it was my try:
JSONObject obj = new JSONObject();
obj.put("imie", field1.getText());
obj.put("nazwisko", field2.getText());
try (FileWriter Data = new FileWriter("Data.JSON")) {
Data.write(obj.toJSONString());
Data.write(obj1.toJSONString());
} catch (IOException e1) {
e1.printStackTrace();
}
but i dont get "Patient2" and it overwriting my first patient if i press save button instead of add new one.
You should be using JSONArray to store several JSONObject instances:
// build object
JSONObject obj = new JSONObject();
obj.put("name", field1.getText());
obj.put("surname", field2.getText());
// build "patient"
JSONObject patient = new JSONObject();
patient.put("patient", obj);
// build another object
JSONObject obj1 = new JSONObject();
obj1.put("name", "Roger");
obj1.put("surname", "Federer");
// build another patient
JSONObject patient1 = new JSONObject();
patient1.put("patient1", obj1);
// create array and add both patients
JSONArray arr = new JSONArray();
arr.put(patient);
arr.put(patient1);
try (FileWriter Data = new FileWriter("Data.JSON")) {
Data.write(arr.toString(4)); // setting spaces for indent
} catch (IOException e1) {
e1.printStackTrace();
}
This code produces JSON:
[
{
"patient": {
"surname": "Doe",
"name": "John"
}
},
{
"patient1": {
"surname": "Federer",
"name": "Roger"
}
}
]

Writing an object array to a JSON file with Gson

I want to write an array of objects to a JSON file. For example:
public class Passanger{
private String name;
private String surname;
}
I want to create object array(Passenger[] Passengers) and save it as a JSON file
with Gson. JSON example:
[
{"name": "jack", "surname": "dere"},
{"name": "adam", "surname": "ered"}
]
To write JSON's data structure you can use for example
public void toFillData() {
JSONObject obj = new JSONObject();
JSONArray list = new JSONArray();
JSONArray listP = new JSONArray();
//Cycle for passengers
list.add("of_name");
list.add("of_surname");
// To build one passenger like json object
obj.put("passenger", list);
// To add passenger to list of passengers
listP.add(obj);
try {
// Save to file
FileWriter file = new FileWriter(fn);
file.write(obj.toJSONString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
//Print on console
System.out.print(obj);
}

How to access nested elements of JSON data in Java?

I'm getting JSON data from a url and I want to show the data on my website. I am successfully showing all JSON data except JSON Hierarchy (JSON Object) data. I am able to access JSONArray person and error data. But, I am not able to access hierarchy (JSON Object) updated data.
I want to access updated.time.
import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
public class ParseJson1 {
public static void main(String[] args) {
String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2";
/*
{
"person": [
{
"name": "John",
"city": "Mumbai"
},
{
"name": "Rahul",
"city": "Delhi"
},
{
"name": "Sanjana",
"city": "Amritsar"
},
{
"name": "Anjali",
"city": "Hyderabad"
},
{
"name": "Mukund",
"city": "Bangalore"
},
{
"name": "Raunak",
"city": "Patna"
}
],
"updated": {
"time": "14:17:48",
"date": "2016-04-10"
},
"error": "2353"
}
*/
try {
String genreJson = IOUtils.toString(new URL(url));
JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
// get the error
System.out.println(genreJsonObject.get("error"));
//Get Array Values
JSONArray genreArray = (JSONArray) genreJsonObject.get("person");
// get the first genre
JSONObject firstGenre = (JSONObject) genreArray.get(0);
System.out.println(firstGenre.get("name"));
// get the Second
JSONObject firstGenre = (JSONObject) genreArray.get(1);
System.out.println(firstGenre.get("name"));
// get the third
JSONObject firstGenre = (JSONObject) genreArray.get(2);
System.out.println(firstGenre.get("city"));
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}
This json Result appears what you got from your api URL . Right ??
{
"person":[
{
"name":"John",
"city":"Mumbai"
},
{
"name":"Rahul",
"city":"Delhi"
},
{
"name":"Sanjana",
"city":"Amritsar"
},
{
"name":"Anjali",
"city":"Hyderabad"
},
{
"name":"Mukund",
"city":"Bangalore"
},
{
"name":"Raunak",
"city":"Patna"
}
],
"updated":{
"time":"14:17:48",
"date":"2016-04-10"
},
"error":"2353"
}
Now Here is a Code how to Iterate or parse your json Object. I Suppose that above Result json is stored in a String Variable String genreJson as per Your Code.
Here I wrote a method to solve your Problem. You may take a reference of it and may try your own code.
public void testYourJSON(String genreJson){
JSONParser parser=new JSONParser(); //parser used to parse String to Correct Json format.
JSONObject obj_ComplexData = (JSONObject) parser.parse(genreJson); // Now Your String Converted to a JSONObject Type.
//person tag Array Data is fetched and Stored into a JSONArray Object.
JSONArray obj_arrayPersonData = (JSONArray) parser.parse(obj_ComplexData.get("person").toString());
for (Object person : obj_arrayPersonData ) { //Iterate through all Person Array.
System.out.println(person.get("name"));
System.out.println(person.get("city"));
}
//Select "updated" Tag Json Data.
JSONObject obj_Updated = (JSONObject) parser.parse(obj_ComplexData.get("updated").toString());
System.out.println(obj_Updated.get("time")); //display time tag.
System.out.println(obj_Updated.get("date")); //display date tag.
System.out.println(obj_Updated.get("error")); //display Your Error.
}
Try this
public static String[] getInfo(String url)
{
String result=//I am assuming your json response is in result
String[] titles=null;
try {
JSONObject jsonObject=new JSONObject(result);
JSONObject temp=null;
JSONArray jsonArray=jsonObject.getJSONArray("person");
int length=jsonArray.length();
person=new String[length];
for (int i=0;i<length;i++){
temp= (JSONObject) jsonArray.get(i);
titles[i]=temp.getString("name")+temp.getString("city");
}
} catch (JSONException e) {
e.printStackTrace();
}
return titles;
}
This works fine, if you face any problem write in comments.
Happy coding!!

How to create multiple JSON array

I was looking this for creating JSON and the output is
{
"age":100,
"name":"mkyong.com",
"messages":["msg 1","msg 2","msg 3"]
}
But i want an array of 10 times like this
{
"engine": "Trident",
"browser": "Internet Explorer 4.0",
"platform": "Win 95+",
},
{
"engine": "Trident",
"browser": "Internet Explorer 5.0",
"platform": "Win 95+",
},
{
"engine": "Trident",
"browser": "Internet Explorer 5.5",
"platform": "Win 95+",
},
And this is the way I tried
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class TestJson {
public static void main(String[] args) {
JSONObject obj=null;
obj = new JSONObject();
for(int i=0;i<10;i++)
{
obj.put("engine", "mkyong.com");
obj.put("browser", i);
obj.put("platform", i);
//obj.put("messages", list);
}
try {
FileWriter file = new FileWriter("c:\\test.json");
file.write(obj.toJSONString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(obj);
}
}
but this only prints 1 json
{
"engine": "Trident",
"browser": "Internet Explorer 4.0",
"platform": "Win 95+",
}
you can do this:
JSONObject jsonObject = new JSONObject();
JSONArray array = new JSONArray();
for(int i=0;i<10;i++){
JSONObject obj = new JSONObject();
obj.put("engine", "mkyong.com");
obj.put("browser", i);
obj.put("platform", i);
//if you are using JSON.simple do this
array.add(obj);
//and if you use json-jena
array.put(obj);
}
jsonObject.put("MyArray" , array);
System.out.print(jsonObject);
In the following code
JSONObject obj=null;
obj = new JSONObject();
for(int i=0;i<10;i++)
{
obj.put("engine", "mkyong.com");
obj.put("browser", i);
obj.put("platform", i);
//obj.put("messages", list);
}
you are creating a single JSONObject and overwriting its values 10 times.
Why are you working with a JSONObject when you want a JSON array?
Create a JSONArray and add 10 JSONObject objects to it.

Parse multiple items in JSON into an array

I have a client that retrieves some json from this page. The json content looks like this:
{
"0": {
"name": "McDonalds 2",
"address": "892 West 75th Street, Naperville, IL 60540"
},
"1": {
"name": "McDonalds 1",
"address": "1298 South Naper Boulevard, Naperville, IL 60540"
},
"2": {
"name": "Burger King 1",
"address": "2040 Aurora Avenue, Naperville, IL, 60540"
}
}
I'm having problems parsing it. I always get an exception when trying to parse anything. It's my first time doing json so I might be doing something really bad. This is my code:
public static void parse(String jsonData)
{
JSONObject jsonObject = new JSONObject();
try
{
jsonObject = new JSONObject(jsonData);
}
catch (JSONException e)
{
e.printStackTrace();
}
try
{
// exception happens here when trying to access data
JSONObject name = ((JSONArray)jsonObject.get("0")).getJSONObject(0)
.getJSONObject("name");
JSONObject address = ((JSONArray)jsonObject.get("0")).getJSONObject(0)
.getJSONObject("address");
} catch (JSONException e) {}
}
How an I retrieve the name and address of each json item to convert it into a restaurant object?
The format of the JSON is wrong. Please refer to this link and the right code is below. You will know what to do.
public static void parse(String jsonData) {
ArrayList<Restaurant> restaurantList= new ArrayList<Restaurant>();
JSONObject jsonObject;
JSONObject jsonRestaurant;
try {
jsonObject= new JSONObject(jsonData);
for(int i=0;i<3;i++) {
Restaurant restaurant= new Restaurant();
jsonRestaurant= jsonObject.getJSONObject(Integer.toString(i));
restaurant.name= jsonRestaurant.getString("name");
restaurant.address= jsonRestaurant.getString("address");
restaurantList.add(restaurant);
}
}
catch(JSONException e) {
e.printStackTrace();
}
}

Categories