|
|
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?
|
|
|
What is servlet context?
The servlet context is an interface which helps to communicate with
other servlets. It contains information about the Web application and
container. It is kind of application environment. Using the context, a
servlet can obtain URL references to resources, and store attributes that
other servlets in the context can use.
Never argue with a fool, onlookers may not be able to tell the difference.
-- Mark Twain
|