|
|
How to create Json Array using Streaming Model API?
This page shows how to create Json array object using Streaming API Model.
Note: Refer How to read Json data using JsonReader? page for dependent libraries.
Java example to create json array object using generator:
package com.javaapi.json.examples;
import java.io.StringWriter;
import javax.json.Json;
import javax.json.stream.JsonGenerator;
public class CreateJsonObjGenEx {
public static void main(String a[]){
StringWriter strWtr = new StringWriter();
JsonGenerator jsonGen = Json.createGenerator(strWtr);
JsonGenerator start = jsonGen.writeStartObject();
start.write("emp_name", "Nataraj G");
start.write("emp_id", 1016);
start.write("salary", 20000);
// create Json array with only values
JsonGenerator plnArrGen = start.writeStartArray("direct_contacts");
plnArrGen.write("Rakesh");
plnArrGen.write("John");
plnArrGen.writeEnd();
// create an array of key-value pairs
JsonGenerator kvArrGen = start.writeStartArray("contacts");
// create each key-value pair as seperate object and add it to the array
kvArrGen.writeStartObject().write("email", "[email protected]").writeEnd();
kvArrGen.writeStartObject().write("mobile", "123123123123").writeEnd();
kvArrGen.writeEnd();
start.writeEnd();
jsonGen.close();
System.out.println(strWtr.toString());
}
}
|
|
Output: |
{
"emp_name": "Nataraj G",
"emp_id": 1016,
"salary": 20000,
"direct_contacts": [
"Rakesh",
"John"
],
"contacts": [
{
"email": "[email protected]"
},
{
"mobile": "123123123123"
}
]
}
|
|
|
|
|
Java API for JSON processing examples
- How to read Json data using JsonReader?
- How to read Json array data using JsonArray?
- How to create Json Object using Object Model?
- How to create Json Array using Object Model?
- How to create Json Object using Streaming Model API?
- How to create Json Array using Streaming Model API?
|
|
|
Can interface be final?
No. We can not instantiate interfaces, so in order to make interfaces
useful we must create subclasses. The final keyword makes a class unable
to be extended.
I respect faith, but doubt is what gets you an education.
-- Wilson Mizner
|