|
|
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?
|
|
|
Transient and Volatile Modifiers
Transient: The transient modifier applies to variables only and it is not stored as part of its object's Persistent state.
Transient variables are not serialized.
Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can
be changed unexpectedly by other parts of the program.
The very best thing you can do for the whole world is to make the most of yourself.
-- Wallace Wattles
|