Writing json files in java

How to write JSON to a file using Jackson

In this quick tutorial, you’ll learn how to write JSON data to a file by using the Jackson API. Jackson is a popular JSON processing library for reading, writing, and parsing JSON data in Java.

implementation 'com.fasterxml.jackson.core:jackson-databind:2.10.0' 
dependency> groupId>com.fasterxml.jackson.coregroupId> artifactId>jackson-databindartifactId> version>2.10.0version> dependency> 

To write a Java Map to a JSON file, you can use the writeValue() method from ObjectMapper as shown below:

try  // create a map MapString, Object> map = new HashMap>(); map.put("name", "John Deo"); map.put("email", "john.doe@example.com"); map.put("roles", new String[]"Member", "Admin">); map.put("admin", true); // create object mapper instance ObjectMapper mapper = new ObjectMapper(); // convert map to JSON file mapper.writeValue(Paths.get("user.json").toFile(), map); > catch (Exception ex)  ex.printStackTrace(); > 
"roles":["Member","Admin"],"name":"John Deo","admin":true,"email":"john.doe@example.com"> 

Let us first create a simple Java class named Book.java that we will use to convert a Java Object to a JSON file: Book.java

public class Book  private String title; private String isbn; private long year; private String[] authors; public Book()  > public Book(String title, String isbn, long year, String[] authors)  this.title = title; this.isbn = isbn; this.year = year; this.authors = authors; > // getters and setters, equals(), toString() . (omitted for brevity) > 
try  // create book object Book book = new Book("Thinking in Java", "978-0131872486", 1998, new String[]"Bruce Eckel">); // create object mapper instance ObjectMapper mapper = new ObjectMapper(); // convert book object to JSON file mapper.writeValue(Paths.get("book.json").toFile(), book); > catch (Exception ex)  ex.printStackTrace(); > 
"title":"Thinking in Java","isbn":"978-0131872486","year":1998,"authors":["Bruce Eckel"]> 

Just like a single Java Object, you can also write a list of Java Objects to a JSON file using the same writeValue() method:

try  // create a books list ListBook> books = Arrays.asList( new Book("Thinking in Java", "978-0131872486", 1998, new String[]"Bruce Eckel">), new Book("Head First Java", "0596009208", 2003, new String[]"Kathy Sierra", "Bert Bates">) ); // create object mapper instance ObjectMapper mapper = new ObjectMapper(); // convert book object to JSON file mapper.writeValue(Paths.get("books.json").toFile(), books); > catch (Exception ex)  ex.printStackTrace(); > 
["title":"Thinking in Java","isbn":"978-0131872486","year":1998,"authors":["Bruce Eckel"]>, "title":"Head First Java","isbn":"0596009208","year":2003,"authors":["Kathy Sierra","Bert Bates"]>] 
try  // create book object Book book = new Book("Thinking in Java", "978-0131872486", 1998, new String[]"Bruce Eckel">); // create object mapper instance ObjectMapper mapper = new ObjectMapper(); // create an instance of DefaultPrettyPrinter ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter()); // convert book object to JSON file writer.writeValue(Paths.get("book.json").toFile(), book); > catch (Exception ex)  ex.printStackTrace(); > 
 "title" : "Thinking in Java", "isbn" : "978-0131872486", "year" : 1998, "authors" : [ "Bruce Eckel" ] > 

For more Jackson examples, check out the How to read and write JSON using Jackson in Java tutorial. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Write a json file in java

I want to write a json file in java, but it doesn’t work, I get this warning: I want to know how to do this, because I am going to convert a cfg file that is tabbed to json.

Type safety: The method add(Object) belongs to the raw type ArrayList. References to generic type ArrayList should be parameterized 
package json; import java.io.File; import java.io.FileWriter; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class JsonWriter < public static void main(String[] args) < JSONObject countryObj = new JSONObject(); countryObj.put("Name", "India"); countryObj.put("Population", new Integer(1000000)); JSONArray listOfStates = new JSONArray(); listOfStates.add("Madhya Pradesh"); listOfStates.add("Maharastra"); listOfStates.add("Rajasthan"); countryObj.put("States", listOfStates); try < // Writing to a file File file=new File("JsonFile.json"); file.createNewFile(); FileWriter fileWriter = new FileWriter(file); System.out.println("Writing JSON object to file"); System.out.println("-----------------------"); System.out.print(countryObj); fileWriter.write(countryObj.toJSONString()); fileWriter.flush(); fileWriter.close(); >catch (IOException e) < e.printStackTrace(); >> > 

IIRC this JSON library is simply quite old and doesn’t support generics, this is why you get this warning. You can ignore it.

1 Answer 1

I would suggest that you just make a simple ArrayList with your objects, and then serialize them into JSON with a serializer (Using the Jackson library in the example below). It would look something like this:

First, define your model in a class (Made without incapsulations for readability):

public class Country < public String name; public Integer population; public Liststates; > 

Then you can go ahead and create it, and populate the list:

import java.io.File; import java.io.IOException; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; public class JsonWriter < public static void main(String[] args) < Country countryObj = new Country(); countryObj.name = "India"; countryObj.population = 1000000; ListlistOfStates = new ArrayList(); listOfStates.add("Madhya Pradesh"); listOfStates.add("Maharastra"); listOfStates.add("Rajasthan"); countryObj.states = listOfStates ; ObjectMapper mapper = new ObjectMapper(); try < // Writing to a file mapper.writeValue(new File("c:\\country.json"), countryObj ); >catch (IOException e) < e.printStackTrace(); >> > 

Источник

Writing to a json file in java using gson

I am creating a java program which reads and writes data to json file using Gson libraries. In that when I write the new data to that json file it is written on the end of the file but not inside the object in json. This is my json content:

private static void writetojson(Hisab hi) < try < FileOutputStream os=new FileOutputStream(file,true); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os)); Gson gson=new GsonBuilder().setPrettyPrinting().create(); String temp=gson.toJson(hi); bw.append(temp); bw.close(); >catch (FileNotFoundException e) < e.printStackTrace(); >catch (IOException e)
public class Hisab < String empname; String position; public String getempname() < return empname; >public void setempname(String empname) < this.empname = empname; >public String getposition() < return position; >public void setposition(String opsition) < this.position = position; >> 

bw.append(temp) simply places the temp at the end of the json file. You need to drill down into the employees array and then put the desired object inside this array

@SarveshKumarSingh i just add the content to object.and pass the object to writetojson method.I open the file in append mode

First of all you need to read the json from file. Convert it to Java object using an appropriate DTO, then append the new Hisab’s to the list in this Object. Now dump it to the file again.

3 Answers 3

Your approach suffers several problems, the first of it being that you risk losing both the original and the new content if appending fails for some reason.

What is more, your storage format is rather strange; why the single object key? It’s not needed; just scrap it, and store the array directly.

Now, I don’t do Gson but Jackson, so I can’t help you with the actual code but basically your code should look like this:

final Charset cs = StandardCharsets.UTF_8; final Path toReplace = Paths.get("whereverisyourfile"); final Path newContents = toReplace.resolveSibling("newcontents.json"); try ( final BufferedReader reader = Files.newBufferedReader(toReplace, cs); final BufferedWriter writer = Files.newBufferedWriter(newContents, cs, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); ) < // read old content, manipulate, write new contents >// IOException is THROWN, not logged Files.move(newContents, toReplace, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); 

Now, as to how to read old content and write, you have two options:

  • read the whole thing as a POJO which you modify before writing;
  • use the streaming API of your library.

The above is your choice and depends on the size of the data stored etc.

And this method should THROW the IOException if any, so that you can deal with anomalous situations. Just printStackTrace() ing an exception is never the good option.

Источник

JSON.simple – Read and Write JSON

JSON.simple is a lightweight JSON processing library that can be used to read and write JSON files and strings. The encoded/decoded JSON will be in full compliance with JSON specification (RFC4627).

JSON.simple library is pretty old and has not been updated since march, 2012. Google GSON library is a good option for reading and writing JSON.

In this Java JSON tutorial, we will first see a quick example of writing to a JSON file and then we will read JSON from the file.

  • Full compliance with JSON specification (RFC4627).
  • Supports encode, decode/parse and escape JSON.
  • Easy to use by reusing Map and List interfaces.
  • Supports streaming output of JSON text.
  • High performance.
  • No dependency on external libraries.

Update pom.xml with json-simple maven dependency.

 com.googlecode.json-simple json-simple 1.1.1 

To write JSON test into the file, we will be working with mainly two classes:

  1. JSONArray : To write data in json arrays. Use its add() method to add objects of type JSONObject .
  2. JSONObject : To write json objects. Use it’s put() method to populate fields.

After populating the above objects, use FileWriter instance to write the JSON file.

package com.howtodoinjava.demo.jsonsimple; import java.io.FileWriter; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class WriteJSONExample < @SuppressWarnings("unchecked") public static void main( String[] args ) < //First Employee JSONObject employeeDetails = new JSONObject(); employeeDetails.put("firstName", "Lokesh"); employeeDetails.put("lastName", "Gupta"); employeeDetails.put("website", "howtodoinjava.com"); JSONObject employeeObject = new JSONObject(); employeeObject.put("employee", employeeDetails); //Second Employee JSONObject employeeDetails2 = new JSONObject(); employeeDetails2.put("firstName", "Brian"); employeeDetails2.put("lastName", "Schultz"); employeeDetails2.put("website", "example.com"); 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 (FileWriter file = new FileWriter("employees.json")) < //We can write any JSONArray or JSONObject instance to the file file.write(employeeList.toJSONString()); file.flush(); >catch (IOException e) < e.printStackTrace(); >> >

To read JSON from file, we will use the JSON file we created in the previous example.

  1. First of all, we will create JSONParser instance to parse JSON file.
  2. Use FileReader to read JSON file and pass it to parser.
  3. Start reading the JSON objects one by one, based on their type i.e. JSONArray and JSONObject .
package com.howtodoinjava.demo.jsonsimple; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class ReadJSONExample < @SuppressWarnings("unchecked") public static void main(String[] args) < //JSON parser object to parse read file JSONParser jsonParser = new JSONParser(); try (FileReader reader = new FileReader("employees.json")) < //Read JSON file Object obj = jsonParser.parse(reader); JSONArray employeeList = (JSONArray) obj; System.out.println(employeeList); //Iterate over employee array employeeList.forEach( emp ->parseEmployeeObject( (JSONObject) emp ) ); > catch (FileNotFoundException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >catch (ParseException e) < e.printStackTrace(); >> private static void parseEmployeeObject(JSONObject employee) < //Get employee object within list JSONObject employeeObject = (JSONObject) employee.get("employee"); //Get employee first name String firstName = (String) employeeObject.get("firstName"); System.out.println(firstName); //Get employee last name String lastName = (String) employeeObject.get("lastName"); System.out.println(lastName); //Get employee website name String website = (String) employeeObject.get("website"); System.out.println(website); >>
[ >, > ] Lokesh Gupta howtodoinjava.com Brian Schultz example.com

Источник

Читайте также:  Python threading exit thread
Оцените статью