In this post, we will learn how to create a JSON object from Java object using JSON-P library.
Check out complete JSON-P tutorial at Java JSON Processing Tutorial.
Check out complete JSON-P tutorial at Java JSON Processing Tutorial.
The code example is available at my Github repository.
- Check out complete JSON-P tutorial at Java JSON Processing Tutorial.
- Check out the Jackson JSON tutorial at https://www.javaguides.net/p/java-jackson-json-tutorial-with-examples.html.
- Check out google GSON tutorial at Google GSON Tutorial.
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).
Read more about JSON-P at official documentation - https://javaee.github.io/jsonp.
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.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1</version>
</dependency>
Let's create a JSON file named "posts.json":
{
"id": 100,
"title": "JSONP Tutorial",
"description": "Post about JSONP",
"content": "HTML content here",
"tags": [
"Java",
"JSON"
]
}
We have Java bean classes that represent above JSON format as:
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 Create JSON Example
In the below example, JsonGenerator writes JSON data to an output source in a streaming way. The JsonGeneratorFactory contains methods to create JsonGenerator instances.
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.stream.JsonGenerator;
import javax.json.stream.JsonGeneratorFactory;
/**
* Class to create a json using jsonp library.
* @author Ramesh fadatare
*
*/
public class CreateJSON {
public static void main(String[] args) throws FileNotFoundException {
OutputStream fos = new FileOutputStream("posts.json");
Map < String, Boolean > config = new HashMap < String, Boolean > ();
config.put(JsonGenerator.PRETTY_PRINTING, true);
JsonGeneratorFactory factory = Json.createGeneratorFactory(config);
JsonGenerator jsonGenerator = factory.createGenerator(fos);
Post post = createPost();
jsonGenerator.writeStartObject(); // {
jsonGenerator.write("id", post.getId()); // "id":123
jsonGenerator.write("title", post.getTitle());
jsonGenerator.write("description", post.getDescription());
jsonGenerator.write("content", post.getContent());
jsonGenerator.writeStartArray("tags");
for (String tag: post.getTags()) {
jsonGenerator.write(tag);
}
jsonGenerator.writeEnd(); // end of phone num array
jsonGenerator.writeEnd(); // }
jsonGenerator.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;
}
}
Let's understand the above Java create JSON example using JSON-P library.
We create a JSON and store in "posts.json" file:
OutputStream fos = new FileOutputStream("posts.json");
A JsonGenerator is created with a JsonGeneratorFactory. The factory receives configuration data which enable pretty printing:
Map<String, Boolean> config = new HashMap<String, Boolean>();
config.put(JsonGenerator.PRETTY_PRINTING, true);
JsonGeneratorFactory factory = Json.createGeneratorFactory(config);
JsonGenerator jsonGenerator = factory.createGenerator(fos);
``
An object is started with writeStartObject(). It is later ended with writeEnd():
```java
jsonGenerator.writeStartObject();
An array is started with writeStartArray(). It is later ended with writeEnd():
jsonGenerator.writeStartArray("tags");
Convert post object into JSON object:
Post post = createPost();
jsonGenerator.writeStartObject(); // {
jsonGenerator.write("id", post.getId()); // "id":123
jsonGenerator.write("title", post.getTitle());
jsonGenerator.write("description", post.getDescription());
jsonGenerator.write("content", post.getContent());
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 code example is available at my Github repository.
- Check out complete JSON-P tutorial at Java JSON Processing Tutorial.
- Check out the Jackson JSON tutorial at https://www.javaguides.net/p/java-jackson-json-tutorial-with-examples.html.
- Check out google GSON tutorial at Google GSON Tutorial.
Comments
Post a Comment
Leave Comment