- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to serialize a JSON object with JsonWriter using Object Model in Java?
The javax.json.JsonWriter interface can write a JSON object or array structure to an output source. The class javax.json.JsonWriterFactory contains methods to create JsonWriter instances. A factory instance can be used to create multiple writer instances with the same configuration. We can create writers from output source using the static method createWriter() of javax.json.Json class.
Syntax
public static JsonWriter createWriter(Writer writer)
In the below example, we can serialize a JSON object using the JsonWriter interface.
Example
import java.io.StringWriter; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonWriter; public class JsonWriterTest { public static void main(String[] args) { JsonObject jsonObj = Json.createObjectBuilder() .add("name", "Adithya") .add("age", 25) .add("salary", 40000) .add("address", Json.createObjectBuilder().add("street", "Madhapur") .add("city", "Hyderabad") .add("zipCode", "500084") .build() ) .add("phoneNumber", Json.createArrayBuilder().add("9959984000") .add("7702144400") .build() ) .build(); StringWriter stringWriter = new StringWriter(); JsonWriter writer = Json.createWriter(stringWriter); writer.writeObject(jsonObj); writer.close(); System.out.println(stringWriter.getBuffer().toString()); } }
Output
{"name":"Adithya","age":25,"salary":40000,"address":{"street":"Madhapur","city": "Hyderabad","zipCode":"500084"},"phoneNumber":["9959984000","7702144400"]}
- Related Articles
- How to create a JSON Object using Object Model in Java?
- How to create a JSON Array using Object Model in Java?
- How to map the JSON data with Jackson Object Model in Java?
- How to serialize a Polygon object using FabricJS?
- Convert JSON object to Java object using Gson library in Java?\n
- How to convert a Map to JSON object using JSON-lib API in Java?
- How to serialize and deserialize an object in Java?
- How to construct a JSON object from a subset of another JSON object in Java?
- How to add elements to JSON Object using JSON-lib API in Java?
- How to deserialize a JSON to Java object using the flexjson in Java?
- How to convert the JSON object to a bean using JSON-lib API in Java?
- How to convert Java object to JSON using GSON library?
- How to convert Java object to JSON using Jackson library?
- How to convert a JSON object to an enum using Jackson in Java?
- How to convert a bean to JSON object using Exclude Filter in Java?

Advertisements