- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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 create a JSON Array using Object Model in Java?
The javax.json.JsonArray interface can represent an immutable JSON array and provides an unmodifiable list view of the values in the array. A JsonArray object can be created by reading JSON data from an input source and also using a static method createArrayBuilder() of javax.json.Json class. We need to import the javax.json package (download javax.json-api.jar file) in order to execute it.
Syntax
public static JsonArrayBuilder createArrayBuilder()
Example
import java.io.*; import javax.json.*; import javax.json.JsonObjectBuilder; public class JsonArrayTest { public static void main(String[] args) { JsonObjectBuilder builder = Json.createObjectBuilder(); builder.add("Name", "Raja Ramesh"); builder.add("Designation", "Java Developer"); builder.add("Company", "TutorialsPoint"); JsonArray contactInfo = Json.createArrayBuilder().add(Json.createObjectBuilder().add("email", "raja@gmail.com")).add(Json.createObjectBuilder().add("mobile", "9959984000")).build(); builder.add("contactInfo", contactInfo); JsonObject data = builder.build(); StringWriter sw = new StringWriter(); JsonWriter jw = Json.createWriter(sw); jw.writeObject(data); jw.close(); System.out.println(sw.toString()); } }
Output
{"Name":"Raja Ramesh","Designation":"Java Developer","Company":"TutorialsPoint", "contactInfo":[{"email":"raja@gmail.com"},{"mobile":"9959984000"}]}
Advertisements