Java read write json

JSON-P

JSON Processing (JSON-P) is a Java API to process (for e.g. parse, generate, transform and query) JSON messages. It produces and consumes JSON text in a streaming fashion (similar to StAX API for XML) and allows to build a Java object model for JSON text using API classes (similar to DOM API for XML).

Add Dependencies

JSON-P is the reference implementation for Java JSON Processing API. We can use this in maven project by adding the following dependencies:

dependency> groupId>javax.jsongroupId> artifactId>javax.json-apiartifactId> version>1.1version> dependency> dependency> groupId>org.glassfishgroupId> artifactId>javax.jsonartifactId> version>1.1version> dependency>
< "id": 100, "title": "JSONP Tutorial", "description": "Post about JSONP", "content": "HTML content here", "tags": [ "Java", "JSON" ] >
package net.javaguides.jsonp.tutorial; import java.util.Arrays; public class Post < private int id; private String title; private String description; private String content; private String[] tags; public Post() < >public int getId() < return id; > public void setId(int id) < this.id = id; > public String getTitle() < return title; > public void setTitle(String title) < this.title = title; > public String getDescription() < return description; > public void setDescription(String description) < this.description = description; > public String getContent() < return content; > public void setContent(String content) < this.content = content; > public String[] getTags() < return tags; > public void setTags(String[] tags) < this.tags = tags; > @Override public String toString() < return "Post [id=" + id + ", title=" + title + ", description=" + description + ", content=" + content + ", tags=" + Arrays.toString(tags) + "]"; > >

Java JSON Read Example

In this example, we are reading «posts.json» file. We use JsonReader and JsonObject interfaces to read and extract fields and display.

package net.javaguides.jsonp.tutorial; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; import javax.json.JsonValue; /** * Class to read json from a posts.json file. * @author Ramesh fadatare * */ public class ReadJSON < public static void main(String[] args) throws IOException < InputStream fis = new FileInputStream("posts.json"); // create JsonReader object JsonReader jsonReader = Json.createReader(fis); // get JsonObject from JsonReader JsonObject jsonObject = jsonReader.readObject(); // we can close IO resource and JsonReader now jsonReader.close(); fis.close(); // Retrieve data from JsonObject and create Post bean Post post = new Post(); post.setId(jsonObject.getInt("id")); post.setTitle(jsonObject.getString("title")); post.setDescription(jsonObject.getString("description")); post.setContent(jsonObject.getString("content")); // reading arrays from json JsonArray jsonArray = jsonObject.getJsonArray("tags"); String[] tags = new String[jsonArray.size()]; int index = 0; for (JsonValue value: jsonArray) < tags[index++] = value.toString(); > post.setTags(tags); // print post object System.out.println(post.toString()); > >
Post [id=100, title=JSONP Tutorial, description=Post about JSONP, content=HTML content here, tags=["Java", "JSON"]]

Java JSON Write Example

In this example, we write Post Java bean object into JSON file «posts.json». In the below example we use JsonGenerator.PRETTY_PRINTING configuration setting so we can set the writer for pretty printing.

package net.javaguides.jsonp.tutorial; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonWriter; import javax.json.JsonWriterFactory; import javax.json.stream.JsonGenerator; /** * Class to write json to a posts.json file. * @author Ramesh fadatare * */ public class WriteJSON < public static void main(String[] args) throws FileNotFoundException < Post post = createPost(); JsonObjectBuilder postBuilder = Json.createObjectBuilder(); JsonArrayBuilder tagsBuilder = Json.createArrayBuilder(); for (String tag: post.getTags()) < tagsBuilder.add(tag); > postBuilder.add("id", post.getId()) .add("title", post.getTitle()) .add("description", post.getDescription()) .add("content", post.getContent()) .add("tags", tagsBuilder); JsonObject postJsonObject = postBuilder.build(); System.out.println("Post JSON String -> " + postJsonObject); //write to file OutputStream os = new FileOutputStream("posts.json"); JsonWriter jsonWriter = Json.createWriter(os); Map  String, Boolean > config = new HashMap < String, Boolean > (); config.put(JsonGenerator.PRETTY_PRINTING, true); JsonWriterFactory factory = Json.createWriterFactory(config); jsonWriter = factory.createWriter(os); jsonWriter.writeObject(postJsonObject); jsonWriter.close(); > private static Post createPost() < // create a post Post post = new Post(); post.setTitle("JSONP Tutorial"); post.setId(100); post.setDescription("Post about JSONP"); post.setContent("HTML content here"); String[] tags = < "Java", "JSON" >; // create some predefined tags post.setTags(tags); // set tags to post return post; > >

The main JSON-P entry point is the Json class. It provides all the necessary methods to parse and build JSON strings from Java. Json is a singleton containing static factory methods for all relevant elements of the JSON-P API.

JsonObjectBuilder postBuilder = Json.createObjectBuilder(); JsonArrayBuilder tagsBuilder = Json.createArrayBuilder();
postBuilder.add("id", post.getId()) .add("title", post.getTitle()) .add("description", post.getDescription()) .add("content", post.getContent()) .add("tags", tagsBuilder); JsonObject postJsonObject = postBuilder.build();

Writing above created to «posts.json» file and print pretty with JsonGenerator.PRETTY_PRINTING setting:

//write to file OutputStream os = new FileOutputStream("posts.json"); JsonWriter jsonWriter = Json.createWriter(os); MapString, Boolean> config = new HashMapString, Boolean>(); config.put(JsonGenerator.PRETTY_PRINTING, true); JsonWriterFactory factory = Json.createWriterFactory(config); jsonWriter = factory.createWriter(os); jsonWriter.writeObject(postJsonObject); jsonWriter.close();

Источник

How to read and write JSON using JSON.simple in Java

In an earlier article, I wrote about reading and writing JSON files in Java using different open-source libraries. In this article, I will focus on one of those libraries — JSON.simple — to convert Java Objects into JSON and back.

JSON.simple is a lightweight Java library for processing JSON that can be used to read, write, and parse JSON. The produced JSON is fully complaint with JSON specification (RFC4627).

implementation 'com.github.cliftonlabs:json-simple:3.1.0' 
dependency> groupId>com.github.cliftonlabsgroupId> artifactId>json-simpleartifactId> version>3.1.0version> dependency> 

Let us create a simple Java class named Book that we will use to convert Java Objects to JSON and back. JSON.simple requires this class to implement the Jsonable interface as well as override the toJson() method: Book.java

package com.attacomsian; import com.github.cliftonlabs.json_simple.JsonObject; import com.github.cliftonlabs.json_simple.Jsonable; import java.io.IOException; import java.io.Writer; public class Book implements Jsonable  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) @Override public String toJson()  JsonObject json = new JsonObject(); json.put("title", this.title); json.put("isbn", this.isbn); json.put("year", this.year); json.put("authors", this.authors); return json.toJson(); > @Override public void toJson(Writer writable) throws IOException  try  writable.write(this.toJson()); > catch (Exception ignored)  > > > 

JSON.simple provides the Jsoner utility class for converting a Java object to a JSON string, as shown below:

try  // create book object Book book = new Book("Thinking in Java", "978-0131872486", 1998, new String[]"Bruce Eckel">); // convert book object to JSON String json = Jsoner.serialize(book); // prettify JSON json = Jsoner.prettyPrint(json); // print JSON System.out.println(json); > catch (Exception ex)  ex.printStackTrace(); > 
 "year":1998, "isbn":"978-0131872486", "title":"Thinking in Java", "authors":[ "Bruce Eckel" ] > 

You can even write the converted JSON string directly to a file using Jsoner.serialize() :

try  // create a writer BufferedWriter writer = Files.newBufferedWriter(Paths.get("book.json")); // create book object Book book = new Book("Thinking in Java", "978-0131872486", 1998, new String[] "Bruce Eckel">); // convert book object to JSON and write to book.json Jsoner.serialize(book, writer); // close the writer writer.close(); > catch (Exception ex)  ex.printStackTrace(); > 
"year":1998,"isbn":"978-0131872486","title":"Thinking in Java","authors":["Bruce Eckel"]> 

To convert a list of Java objects to a JSON array, all you need to do is just create a List of Book and pass it to Jsoner.serialize() , as shown below:

try  // create a writer BufferedWriter writer = Files.newBufferedWriter(Paths.get("books.json")); // create 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">) ); // convert books list to JSON and write to books.json Jsoner.serialize(books, writer); // close the writer writer.close(); > catch (Exception ex)  ex.printStackTrace(); > 
[  "year": 1998, "isbn": "978-0131872486", "title": "Thinking in Java", "authors": [ "Bruce Eckel" ] >,  "year": 2003, "isbn": "0596009208", "title": "Head First Java", "authors": [ "Kathy Sierra", "Bert Bates" ] > ] 

Unfortunately, there is no direct way to convert a JSON string to a Java Object using JSON.simple. For this, we have to either use the 3rd-party library like Dozer or manually build the object. Let us use the Dozer library by adding the following dependency to your Gradle’s project build.gradle file:

implementation 'com.github.dozermapper:dozer-core:6.5.0' 
dependency> groupId>com.github.dozermappergroupId> artifactId>dozer-coreartifactId> version>6.5.0version> dependency> 
try  // create a reader Reader reader = Files.newBufferedReader(Paths.get("book.json")); // read JSON from a file JsonObject jsonObject = (JsonObject) Jsoner.deserialize(reader); // create a Dozer mapper Mapper mapper = DozerBeanMapperBuilder.buildDefault(); // convert JsonObject to Book Book book = mapper.map(jsonObject, Book.class); // print the book System.out.println(book); // close the reader reader.close(); > catch (Exception ex)  ex.printStackTrace(); > 
Booktitle='Thinking in Java', isbn='978-0131872486', year=1998, authors=[Bruce Eckel]> 

To convert a JSON array to a list of Java Objects, we can use the above example code with a few modifications:

try  // create a reader Reader reader = Files.newBufferedReader(Paths.get("books.json")); // read JSON from a file JsonArray objects = Jsoner.deserializeMany(reader); // create a Dozer mapper Mapper mapper = DozerBeanMapperBuilder.buildDefault(); // convert JsonArray to List JsonArray jsonArray = (JsonArray) objects.get(0); ListBook> books = jsonArray.stream() .map(obj -> mapper.map(obj, Book.class)) .collect(Collectors.toList()); // print all books books.forEach(System.out::println); // close the reader reader.close(); > catch (Exception ex)  ex.printStackTrace(); > 
Booktitle='Thinking in Java', isbn='978-0131872486', year=1998, authors=[Bruce Eckel]> Booktitle='Head First Java', isbn='0596009208', year=2003, authors=[Kathy Sierra, Bert Bates]> 

That’s all folks. In this article, you have learned how to read and write JSON using the JSON.simple library in Java. JSON.simple is no longer actively maintained and is only good for simple use cases. For better JSON serialization/deserialization, you should either use Jackson or Gson. Check out the reading and writing JSON files in Java to learn more about all modern JSON libraries. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Читайте также:  Java control panel ubuntu
Оцените статью