
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
Create 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", "[email protected]")).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":"[email protected]"},{"mobile":"9959984000"}]}
Advertisements