JSON Processing

JSON Processing is defined as the Java API for JSON Processing in JSR 353, and the
complete specification can be downloaded.
JSON (JavaScript Object Notation) is a lightweight data-interchange format. The format
is easy for humans and machines to read and write. JSON was based on a subset of
JavaScript and is commonly used with it, but it is a language-independent data format.
A JSON structure can be built as either of the following:
• A collection of name/value pairs, generally realized as dictionary, hash table, or
associative array
• An ordered list of values, generally realized as an array, list, or sequence
The following example shows the JSON representation of an object that describes a
movie:

{"name": "The Matrix","actors": ["Keanu Reeves","Laurence Fishburne","Carrie-Ann Moss"],"year": 1999}

The object has three name/value pairs. The first name is  name with a string value for the
movie name, the second name is  actors with an array value for the actors in the movie,
and the third name is  year with a number value for the year the movie was released.
JSON is quickly becoming the primary choice for developers for consuming and cre‐
ating web services. Currently, Java applications use different implementation libraries
to produce/consume JSON. These libraries are bundled along with the application,

thereby increasing the overall size of the deployed archive. Java API for JSON Processing
will provide a standard API to parse and generate JSON so that the applications that
use the API are smaller and portable. The goals of the API are to:
• Produce/consume JSON text in a streaming fashion (similar to StAX API for XML)
• Build a Java object model for JSON text (similar to DOM API for XML)
Binding of JSON text to Java objects is outside the scope of this API.

Streaming API

The Streaming API provides a way to parse and generate JSON text in a streaming
fashion. The API provides an event-based parser and allows an application developer
to ask for the next event (i.e., pull the event), rather than handling the event in a callback.
This gives a developer more procedural control over processing of the JSON. Parser
events can be processed or discarded, or the next event may be generated.
The streaming model is adequate for local processing where only specific parts of the
JSON structure need to be accessed, and random access to other parts of the data is not
required. The streaming API is a low-level API designed to process large amounts of
JSON data efficiently. Other JSON frameworks (such as JSON binding) can be imple‐
mented with this API.
The streaming API is similar to the StAX API for XML and consists of the interfaces
JsonParser for consuming JSON and  JsonGenerator for producing JSON.

Consuming JSON Using the Streaming API

JsonParser contains methods to parse JSON data using the streaming model.  Json
Parser provides forward, read-only access to JSON data using the pull parsing pro‐
gramming model. In this model, the application code controls the thread and calls
methods in the parser interface to move the parser forward or to obtain JSON data from
the current state of the parser.
JsonParser can be created from an  InputStream :
JsonParser parser = Json.createParser(new FileInputStream(...));
This code shows how to create a parser from an  InputStream obtained from a new
FileInputStream .
JsonParser can also be created from a  Reader :
JsonParser parser = Json.createParser(new StringReader(...));
This code shows how to create a parser from a  StringReader .
You can create multiple parser instances using  JsonParserFactory :
JsonParserFactory factory = Json.createParserFactory(null);
JsonParser parser1 = factory.createParser(...);
JsonParser parser2 = factory.createParser(...);
The factory can be configured with the specified map of provider-specific configuration
properties. Any unsupported configuration properties specified in the map are ignored.
In this case,  null properties are passed during the creation of the parser factory.
The pull-parsing programming model is used to to parse the JSON. The  next method
returns the event for the next parsing state, which could be any of the following types:
• START_ARRAY• END_ARRAY• START_OBJECT• END_OBJECT• KEY_NAME• VALUE_STRING• VALUE_NUMBER• VALUE_TRUE• VALUE_FALSE• VALUE_NULL
The parser generates  START_OBJECT and  END_OBJECT events for an empty JSON object{ } .
For an object with two name/value pairs:
{"apple":"red","banana":"yellow"}
The events generated are shown in bold:
{START_OBJECT"apple"KEY_NAME:"red"VALUE_STRING,"banana"KEY_NAME:"yellow"VALUE_STRING}
The events generated for an array with two JSON objects are shown in bold:
[START_ARRAY{START_OBJECT"apple"KEY_NAME:"red"VALUE_STRING}END_OBJECT,{START_OBJECT"banana"KEY_NAME:"yellow"VALUE_STRING}END_OBJECT]END_ARRAY
The events generated for a nested structure are shown in bold:

{START_OBJECT"title"KEY_NAME:"TheMatrix"VALUE_STRING,"year"KEY_NAME:1999VALUE_NUMBER,"cast"KEY_NAME:[START_ARRAY"Keanu Reeves"VALUE_STRING,"Laurence Fishburne"VALUE_STRING,"Carrie-Anne Moss"VALUE_STRING]END_ARRAY}END_OBJECT

Producing JSON Using the Streaming API

The Streaming API provides a way to generate well-formed JSON to a stream by writing
one event at a time.
JsonGenerator contains  writeXXX methods to write name/value pairs in JSON objects
and values in JSON arrays:
JsonGeneratorFactory factory = Json.createGeneratorFactory(null);
JsonGenerator gen = factory.createGenerator(System.out);
gen.writeStartObject().writeEnd();
In this code:
• A  JsonGenerator is obtained from  JsonGeneratorFactory and configured to write
the output to  System.out .
The factory can be configured with the specified map of provider-specific config‐
uration properties. Any unsupported configuration properties specified in the map
are ignored. In this case,  null properties are passed during the creation of the
generator factory.
• An empty object, with no name/value pairs, is created and written to the configured
output stream. An object is started when the  writeStartObject method is called,
and ended with the  writeEnd method.
JsonGenerator may be configured to write to a  Writer as well.
The generated JSON structure is:{ }
An object with two name/value pairs can be generated:
gen.writeStartObject().write("apple", "red").write("banana", "yellow").writeEnd();
A name/value pair is written via the  write method, which takes a name as the first
parameter and a value as the second parameter. The value can be  BigDecimal ,  BigIn
teger ,  boolean ,  double ,  int ,  long ,  String , and  JsonValue .

The generated JSON structure is:
{"apple":"red","banana":"yellow"}
An array with two objects with each object with a name/value pair can be generated:
gen.writeStartArray().writeStartObject().write("apple", "red").writeEnd().writeStartObject().write("banana", "yellow").writeEnd().writeEnd();

A new array is started when the  writeStartArray method is called and ended when
the  writeEnd method is called. An object within an array is written via the  writeStar
tObject and  writeEnd methods. The generated JSON structure is:
[{ "apple":"red" },{ "banana":"yellow" }]
A nested structure with two name/value pairs and a named array can be generated:
gen.writeStartObject().write("title", "The Matrix").write("year", 1999).writeStartArray("cast").write("Keanu Reeves").write("Laurence Fishburne").write("Carrie-Anne Moss").writeEnd().writeEnd();
A named array is started via  writeStartArray . Each element of the array is written via
the  write method, which can take values of the type  BigDecimal ,  BigInteger ,  boolean ,
double ,  int ,  long ,  String , and  JsonValue .
The generated JSON structure is:
{"title":"The Matrix","year":1999,"cast":["Keanu Reeves","Laurence Fishburne","Carrie-Anne Moss"]}

Object Model API
The Object Model API is a high-level API that provides immutable object models for
JSON object and array structures. These JSON structures are represented as object
models via the Java types  JsonObject and  JsonArray .  JsonObject provides a  Map view
to access the unordered collection of zero or more name/value pairs from the model.
Similarly,  JsonArray provides a  List view to access the ordered sequence of zero or
more values from the model.
This programming model is most flexible and enables processing that requires random
access to the complete contents of the tree. However, it is often not as efficient as the
streaming model and requires more memory.
The Object Model API is similar to the DOM API for XML and uses builder patterns
to create these object models. It consists of the interfaces  JsonReader (for consuming
JSON) and  JsonObjectBuilder and  JsonArrayBuilder (for producing JSON).

Consuming JSON Using the Object Model API

JsonReader contains methods to read JSON data using the object model from an input
source.
JsonReader can be created from  InputStream :
JsonReader reader = Json.createReader(new FileInputStream(...));
This code shows how to create a new parser from an  InputStream obtained from a new
FileInputStream .
JsonReader can also be created from  Reader :
JsonParser parser = Json.createParser(new StringReader(...));
This code shows how to create a parser from a  StringReader .
You can create multiple parser instances using  JsonReaderFactory :
JsonReaderFactory factory = Json.createReaderFactory(null);
JsonReader parser1 = factory.createReader(...);
JsonReader parser2 = factory.createReader(...);
The factory can be configured with the specified map of provider-specific configuration
properties. Any unsupported configuration properties specified in the map are ignored.
In this case,  null properties are passed during the creation of the reader factory.
An empty JSON object can be read as:
JsonReader jsonReader = Json.createReader(new StringReader("{}"));
JsonObject json = jsonReader.readObject();

In this code, a  JsonReader is initialized via  StringReader , which reads the empty JSON
object. Calling the  readObject method returns an instance of  JsonObject .
An object with two name/value pairs can be read as:
jsonReader = Json.createReader(new StringReader("{"
+ " \"apple\":\"red\","
+ " \"banana\":\"yellow\""
+ "}"));
JsonObject json = jsonReader.readObject();
json.getString("apple");
json.getString("banana");
In this code, the  getString method returns the string value for the specific key in the
object. Other  getXXX methods can be used to access the value based upon the data type.
An array with two objects with each object with a name/value pair can be read as:
jsonReader = Json.createReader(new StringReader("["
+ " { \"apple\":\"red\" },"
+ " { \"banana\":\"yellow\" }"
+ "]"));
JsonArray jsonArray = jsonReader.readArray();
In this code, calling the  readArray method returns an instance of the  JsonArray inter‐
face. This interface has convenience methods to get  boolean ,  integer , and  String
values at a specific index. This interface extends from  java.util.List , so usually the
list operations are available as well.
A nested structure can be read as:
jsonReader = Json.createReader(new StringReader("{"
+ " \"title\":\"The Matrix\","
+ " \"year\":1999,"
+ " \"cast\":["
+ " \"Keanu Reeves\","
+ " \"Laurence Fishburne\","
+ " \"Carrie-Anne Moss\""
+ " ]"
+ "}"));
json = jsonReader.readObject();

Producing JSON Using the Object Model API

JsonObjectBuilder can be used to create models that represent JSON objects. The
resulting model is of type  JsonObject . Similarly,  JsonArrayBuilder can be used to
create models that represent JSON arrays where the resulting model is of type
JsonArray :
JsonObject jsonObject = Json.createObjectBuilder().build();
In this code, a  JsonObjectBuilder is used to create an empty object. An empty object,
with no name/value pairs, is created. The generated JSON structure is:{ }
Multiple builder instances can be created via  JsonBuilderFactory :
JsonBuilderFactory factory = Json.createBuilderFactory(null);
JsonArrayBuilder arrayBuilder = factory.createArrayBuilder();
JsonObjectBuilder objectBuilder = factory.createObjectBuilder();
The factory can be configured with the specified map of provider-specific configuration
properties. Any unsupported configuration properties specified in the map are ignored.
In this case,  null properties are passed during the creation of the reader factory.
The generated  JsonObject can be written to an output stream via  JsonWriter :
Json.createWriter(System.out).writeObject(jsonObject);
In this code, a new  JsonWriter instance is created and configured to write to  Sys
tem.out . The previously created  jsonObject is then written when the  writeObject
method is called.
JsonWriter may be configured to write to a  Writer as well.
An object with two name/value pairs can be generated:
Json.createObjectBuilder().add("apple", "red").add("banana", "yellow").build();
A name/value pair is written via the  add method, which takes a name as the first pa‐
rameter and a value as the second parameter. The value can be  BigDecimal ,  BigInteg
er ,  boolean ,  double ,  int ,  long ,  String ,  JsonValue ,  JsonObjectBuilder , or  JsonAr
rayBuilder . Specifying the value as  JsonObjectBuilder and  JsonArrayBuilder allows
us to create nested objects and arrays.
The generated JSON structure is:
{"apple":"red","banana":"yellow"}
An array with two objects with each object with a name/value pair can be generated:
JsonArray jsonArray = Json.createArrayBuilder().add(Json.createObjectBuilder().add("apple","red")).add(Json.createObjectBuilder().add("banana","yellow")).build();

You start a new array by creating a  JsonArrayBuilder . You write an object within an
array by calling the  add method and creating a new object using the  JsonObjectBuild
er method. The generated JSON structure is:
[{ "apple":"red" },{ "banana":"yellow" }]
The  JsonWriter.writeArray method is called to write an array to the configured output
stream.
A nested structure with two name/value pairs and a named array can be generated:
jsonArray = Json.createArrayBuilder().add(Json.createObjectBuilder()
.add("title", "The Matrix").add("year", 1999).add("cast", Json.createArrayBuilder()
.add("Keanu Reaves").add("Laurence Fishburne").add("Carrie-Anne Moss")))
.build();
You start a named array by calling the  add method, passing the name of the array, and
creating a new array by calling the  Json.createArrayBuilder method. Each element
of the array is written via the  add method, which can take values of the type  BigDeci
mal ,  BigInteger ,  boolean ,  double ,  int ,  long ,  String ,  JsonValue ,  JsonObjectBuild
er , and  JsonArrayBuilder .
The generated JSON structure is:
{"title":"The Matrix","year":1999,"cast":["Keanu Reeves","Laurence Fishburne","Carrie-Anne Moss"]}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值