Processing JSON data

If you use Java RESTful web service frameworks, such as JAX-RS, for building RESTful web APIs, the serialization and deserialization of the request and response messages will be taken care of by the framework. However, understanding the JSON structure and tools for processing JSON will definitely help you when the default offering by the framework does not meet your requirements. The following diagram illustrates the role of the JSON marshalling (converting Java object to JSON format) and unmarshalling components (converting JSON format to Java Object) in a typical Java RESTful web service implementation:

This section will teach you the various processing models for JSON data. By the term processing, we mean reading, writing, querying, and modifying JSON data. Two widely adopted programming models for processing JSON are as follows:

  • Object model: In this model, the entire JSON data is read into memory in a tree format. This tree can be traversed, analyzed, or modified with appropriate APIs. As this approach loads the entire content in the memory first and then starts parsing, it ends up consuming more memory and CPU cycles. However, this model gives more flexibility while manipulating the content.
  • Streaming model: The term streaming is very generic in meaning and can be used in many aspects. In our discussion, this term means that the data can be read or written in blocks. This model does not read the entire JSON content into the memory to get started with parsing; rather, it reads one element at a time. For each token read, the parser generates appropriate events indicating the type of token, such as the start or end of an array, or the start or end of the object and attribute values. A client can process the contents by listening for appropriate events. The most important point is that instead of letting the parser push the content to the client (push parser), the client can pull the information from the parser, as it needs (pull parser). In this model, the client is allowed to skip or stop reading contents in the middle of the process if it has finished reading the desired elements. This model is also useful when you write the content to an output source in blocks.

You may want to consider using streaming APIs in the following situations:

  • When the data is huge in size, and it is not feasible to load the entire content into the memory for processing the content
  • When partial processing is needed and the data model is not fully available yet

We will revisit these two parsing models while discussing tools for processing JSON later in this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.191.134