How to append data JSON in JAVA - java

Hello i have a json file with data exists like this
[
{
"employee": {
"firstName": "Rudi",
"lastName": "Anton"
}
},
{
"employee": {
"firstName": "Syafira",
"lastName": "Zarakaria"
}
}
]
I want to append json data to this file.
My code now not appending data, re-write file.
Help me
This is my code
JSONObject employeeDetails = new JSONObject();
employeeDetails.put("firstName", "Justin");
employeeDetails.put("lastName", "Saklitinov");
JSONObject employeeObject = new JSONObject();
employeeObject.put("employee", employeeDetails);
JSONObject employeeDetails2 = new JSONObject();
employeeDetails2.put("firstName", "Zara");
employeeDetails2.put("lastName", "Lovez");
JSONObject employeeObject2 = new JSONObject();
employeeObject2.put("employee", employeeDetails2);
//Add employees to list
JSONArray employeeList = new JSONArray();
employeeList.add(employeeObject);
employeeList.add(employeeObject2);
//Write JSON file
try{
String strPath = "employee.json";
File strFile = new File(strPath);
boolean fileCreated = strFile.createNewFile();
//File appending
Writer objWriter = new BufferedWriter(new FileWriter(strFile));
//objWriter.write(employeeList.toJSONString());
objWriter.flush();
objWriter.close();
out.flush();
out.print("OK");
} catch (IOException e) {
e.printStackTrace();
}

You should read the json file into an JSONArray. Add new employee data to this JSONArray and write it to the file. I have modified some of your code.
// Read json file
String jsonFileStr = new String(
Files.readAllBytes(Paths
.get("PATH TO YOUR EMPLOYEE JSON")),
StandardCharsets.UTF_8);
System.out.println(jsonFileStr);
JSONArray jsonArray = (JSONArray) new JSONParser().parse(jsonFileStr);
// Create employee data to be add to json file
JSONObject employeeDetails = new JSONObject();
employeeDetails.put("firstName", "Justin");
employeeDetails.put("lastName", "Saklitinov");
JSONObject employeeObject = new JSONObject();
employeeObject.put("employee", employeeDetails);
JSONObject employeeDetails2 = new JSONObject();
employeeDetails2.put("firstName", "Zara");
employeeDetails2.put("lastName", "Lovez");
JSONObject employeeObject2 = new JSONObject();
employeeObject2.put("employee", employeeDetails2);
// Add data to jsonArray read from json file
jsonArray.put(employeeObject);
jsonArray.put(employeeObject2);
// Writing the jsonArray back to file
String strPath = "PATH TO EMPLOYEE JSON";
File strFile = new File(strPath);
boolean fileCreated = strFile.createNewFile();
Writer objWriter = new BufferedWriter(new FileWriter(strFile));
objWriter.write(jsonArray.toString());
objWriter.flush();
objWriter.close();
Note: You might want to reconsider using the same key 'employee' multiple times in the json.

Try BufferedWriter it open a file in append mode.
BufferedWriter out = new BufferedWriter(
new FileWriter(fileName, true));
out.write(str);
out.close();

yes if you are reading as object and writing as on object. It is a overwrite on the same file.

Related

Writing multiple times on a JSON file with Java

I'm trying to write multiple times on a JSON file using JSON-Simple and Java, but I have some problems after the second run. I'm new to JSON so that's just a way to learn about it, here is the code:
public class Writer{
#SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException {
JSONParser parser = new JSONParser();
JSONObject outer = new JSONObject();
JSONObject inner = new JSONObject();
JSONObject data = new JSONObject();
ArrayList<JSONObject> arr = new ArrayList<JSONObject>();
inner.put("Name", "Andrea");
inner.put("Email", "andrea#mail.com");
arr.add(inner);
outer.put("Clienti", arr);
System.out.println("Dati: " + outer);
File file = new File("temp.json");
if(file.exists()) {
PrintWriter write = new PrintWriter(new FileWriter(file));
Iterator<JSONObject> iterator = arr.iterator();
while(iterator.hasNext()) {
JSONObject it = iterator.next();
data = (JSONObject) it;
}
arr.add(data);
outer.put("Clienti", arr);
System.out.println("Dati: " + outer);
write.write(outer.toString());
write.flush();
write.close();
} else {
PrintWriter write = new PrintWriter(new FileWriter(file));
write.write(outer.toString());
write.flush();
write.close();
}
}
}
So, I just wanna try to add the same thing without losing what I added before, but when I run:
The first run goes well, it prints normally on the file.
Result:
Dati: {"Clienti":[{"Email":"andrea#gmail.com","Nome":"Andrea"}]}
The second run too, it adds another field inside the list, keeping the first one too.
Result:
Dati:
{"Clienti":[{"Email":"andrea#gmail.com","Nome":"Andrea"},{"Email":"andrea#gmail.com","Nome":"Andrea"}]}
From the third run it doesn't upload anymore the file, instead of adding another field to the existent 2 it just prints the second result.
I tried many options but still can't understand how to add a third field without losing the previous two, how can i solve this?
Solved putting this on if clause:
if(file.exists()) {
Object obj = parser.parse(new FileReader("temp.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray array = (JSONArray) jsonObject.get("Clienti");
PrintWriter write = new PrintWriter(new FileWriter(file));
Iterator<JSONObject> iterator = array.iterator();
while(iterator.hasNext()) {
JSONObject it = iterator.next();
data = (JSONObject) it;
System.out.println("Data" + data);
arr.add(data);
}
arr.add(inner);
System.out.println(arr);
outer.put("Clienti", arr);
System.out.println("Dati: " + outer);
write.write(outer.toString());
write.flush();
write.close();
}

parsing and reading a json array java

have a structure for a contact book:
Contact { "Name":{ "First name":"Erm","Last Name": "Smith" }, "Number":67485647 }.
I save it as a Json object and than store it in a file with createContact().
public synchronized void createContact (String fname, String lname,String typeof, int number) throws FileNotFoundException
{
JsonObjectBuilder contactBuilder = Json.createObjectBuilder();
JsonObjectBuilder nameBuilder = Json.createObjectBuilder();
JsonArrayBuilder contactArrayBuilder= Json.createArrayBuilder();
nameBuilder.add("First Name",fname);
nameBuilder.add("Last Name",lname);
contactBuilder.add("Name", nameBuilder);
contactBuilder.add("Type", typeof);
contactBuilder.add("number", number);
JsonObject contact = contactBuilder.build();
contactArrayBuilder.add(contact);
JsonArray contactArray=contactArrayBuilder.build();
//write to file
OutputStream os = new FileOutputStream(filename);
JsonWriter fileWriter = Json.createWriter(os);
fileWriter.writeArray(contactArray);
fileWriter.close();
}
I read the file with:
InputStream is = new FileInputStream(filename);
JsonReader fileReader = Json.createReader(is);
JsonArray contactObj = (JsonArray) Json.createParserFactory(fileReader.readObject());
JsonArrayBuilder contactArrayBuilder= Json.createArrayBuilder();
This is when I get the error
javax.json.JsonException: Cannot read JSON object, found JSON array
at org.glassfish.json.JsonReaderImpl.readObject(JsonReaderImpl.java:105)
I am using javax.json
The problem is that you are storing a JsonArray in that file, and then trying to read that JsonArray as a JsonObject. What you can do to get your code to work is remove these lines:
JsonArray contactObj = (JsonArray) Json.createParserFactory(fileReader.readArray());
JsonArrayBuilder contactArrayBuilder= Json.createArrayBuilder();
and replace them with something like this:
JsonArray array = fileReader.readArray();
In the end, reading the file will look like this:
InputStream is = new FileInputStream(filename);
JsonReader fileReader = Json.createReader(is);
JsonArray array = fileReader.readArray();
Change this line
JsonArray contactObj = (JsonArray) Json.createParserFactory(fileReader.readObject());
to this
JsonArray contactObj = (JsonArray) Json.createParserFactory(fileReader.readArray());
as you are expecting an array but reading the object you are getting this error.

Spring MVC can not fetch JSON value

In Spring mvc I have a mytable.json file.
I want to fetch that json file data and then want to add to model.addAttribute().
mytable.json
{"name1":["place1.1","place1.2"],
"name2":["place2.1","place1.2"]
...........
.........}
I want to fetch the names with their corresponding citylist.
Ex:
name1=place1.1,place1.2
so,I have done:--
try {
JSONParser parser = new JSONParser();
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("file/mytable.json").getFile());
JSONObject obj = (JSONObject) parser.parse(new FileReader(file));
Iterator<String> keys = obj.values().iterator();
while( keys.hasNext() )
{
String key = (String)keys.next();
if ( obj.get(key) instanceof JSONObject )
{
model.addAttribute("key", key);
}
}
} catch (Exception e) {
e.printStackTrace();
}
But I am getting error:
Unexpected character (�) at position 0.
in this line :
JSONObject obj = (JSONObject) parser.parse(new FileReader(file));
why??Where is the problem?
The JSONParser parser = new JSONParser(); is expecting a JSON String, not a .json file. hence the Unexpected character.... error.
You can InputStreamReader:
jsonObject = (JSONObject) parser.parse(new InputStreamReader(new FileInputStream("file/mytable.json")));

Parse JSON response into a List

I'm trying to parse a JSON response
it's structure is:
{
"metric": {
"name": "string",
"values": [
"string"
]
}
}
My code so far:
StringBuilder sb = new StringBuilder();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
wr.close();
reader.close();
JSONObject json = new JSONObject(sb.toString());
JSONArray jsonArray = json.getJSONArray("values");
List<String> list = new ArrayList<>();
String errorPercent ="";
for(int i = 0 ; i < json.length() ; i++){
errorPercent = jsonArray.getJSONArray(i).getString(i);
list.add(errorPercent);
}
The output I'm getting is saying that "values " was not found,
am I misunderstanding the structure of the JSON response?
Edit
It appears the structure I was given on the site I'm receiving the response from is not correct. it appears to be a more complicated structure
I have modified my code accordingly:
JSONObject json = new JSONObject(sb.toString());
JSONObject metricsData = json.getJSONObject("metric_data");
JSONArray metrics = metricsData.getJSONArray("metrics");
System.out.println(metrics.toString());
The print out is as follows:
[{"timeslices":[{"values":{"max_response_time":0,"calls_per_minute":0,"average_be_response_time":0,"error_percentage":0,"min_response_time":0,"requests_per_minute":0,"average_network_time":0,"average_response_time":0,"average_fe_response_time":0,"total_app_time":0,"call_count":0,"fe_time_percentage":0,"total_network_time":0,"total_fe_time":0,"network_time_percentage":0},"from":"2015-10-25T22:39:00+00:00","to":"2015-10-25T22:40:00+00:00"},{"values":{"max_response_time":0,"calls_per_minute":0,"average_be_response_time":0,"error_percentage":0,"min_response_time":0,"requests_per_minute":0,"average_network_time":0,"average_response_time":0,"average_fe_response_time":0,"total_app_time":0,"call_count":0,"fe_time_percentage":0,"total_network_time":0,"total_fe_time":0,"network_time_percentage":0},
There appears to be another array within the array: "timeslices" is that right? how do I get at that array?
I unsuccessfully tried:
JSONArray timeslices = metrics.getJSONArray("timeslices");
values is a field inside metric.
You'd need to first get the metric object, then look inside that for values.
JSONObject metric = json.getJSONObject("metric");
JSONArray jsonArray = metric.getJSONArray("values");

JSON Text data reading in Java

I have text file with JSON data in it with following format:
[ {
"belongs_to_suite": "no",
"belongs_to_suite_id": "",
"brand_family": "",
"cat_manufacturer_id": 4382,
"cat_sw_edition_id": null,
"cat_sw_product_id": 38,
"cat_sw_release_id": 47354894, } ]
I want to read only brand_family, for which I suppose I need a JSON array.
Do I need to define this format using JSON objects first?
I have downloaded org.json lib, and I have following code in which I am reading the text file, but I cannot find out how do I define format and then import all data in [{}...{}] into an array and:
FileInputStream fstream = new FileInputStream("file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
try {
JSONObject obj = new JSONObject(br);
String n = obj.getString("version");
//int a = obj.getInt("age");
System.out.println(n);
}
As mentioned in the comments, your JSON is an array, so firstly you should call:
JSONArray array = new JSONArray(br);
Then you can do something with the size or get the first object:
JSONObject first = array.getJSONObject(0);
And finally, having the JSONObject, you can extract and process any field:
System.out.println(first.getString(""));
You can do it simply as below :
JSONParser parser=new JSONParser();
try {
JSONObject jsonObject = (JSONObject) parser.parse(new InputStreamReader(new FileInputStream("D://jsontest.txt")));
JSONArray lang= (JSONArray) jsonObject.get("obj");
for(int i=0; i<lang.size(); i++){
JSONObject obj=(JSONObject) lang.get(i);
System.out.println(obj.get("brand_family"));
}
}catch(Exception e){
e.printStackTrace();
}
Change your file to below :
{
"obj": [
{
"belongs_to_suite": "no",
"belongs_to_suite_id": "",
"brand_family": "1",
"cat_manufacturer_id": 4382,
"cat_sw_edition_id": null,
"cat_sw_product_id": 38,
"cat_sw_release_id": 47354894
},
{
"belongs_to_suite": "yes",
"belongs_to_suite_id": "",
"brand_family": "2",
"cat_manufacturer_id": 4382,
"cat_sw_edition_id": null,
"cat_sw_product_id": 38,
"cat_sw_release_id": 47354894
}
]
}

Categories

Resources