
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Serialize 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"]}
Advertisements