How to work with json in java

Java API for JSON Processing: An Introduction to JSON

JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write. JSON can represent two structured types: objects and arrays. An object is an unordered collection of zero or more name/value pairs. An array is an ordered sequence of zero or more values. The values can be strings, numbers, booleans, null, and these two structured types.

Listing 1 is an example from Wikipedia that shows the JSON representation of an object that describes a person. The object has string values for first name and last name, a number value for age, an object value representing the person’s address, and an array value of phone number objects.

Listing 1. Example of JSON representation of an object

JSON is often used in Ajax applications, configurations, databases, and RESTful web services. All popular websites offer JSON as the data exchange format with their RESTful web services.

JSON Processing

The Java API for JSON Processing (JSR 353) provides portable APIs to parse, generate, transform, and query JSON using object model and streaming APIs.

The object model API creates a random-access, tree-like structure that represents the JSON data in memory. The tree can then be navigated and queried. This programming model is the 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.

Читайте также:  Java break double for

The streaming API provides a way to parse and generate JSON in a streaming fashion. It hands over parsing and generation control to the programmer. The streaming API provides an event-based parser and allows an application developer to ask for the next event rather than handling the event in a callback. This gives a developer more procedural control over the JSON processing. Application code can process or discard the parser event and ask for the next event (pull the event). The streaming model is adequate for local processing where random access of other parts of the data is not required. Similarly, the streaming API provides a way to generate well-formed JSON to a stream by writing one event at a time.

The Object Model API

The object model API is similar to the Document Object Model (DOM) API for XML. It is a high-level API that provides immutable object models for JSON object and array structures. These JSON structures are represented as object models using the Java types JsonObject and JsonArray . Table 1 lists the main classes and interfaces in the object model API.

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.

Table 1. Main classes in the object model API

JsonObject , JsonArray , JsonString , and JsonNumber are subtypes of JsonValue . These are constants defined in the API for null, true, and false JSON values.

The object model API uses builder patterns to create these object models from scratch. Application code can use the interface JsonObjectBuilder to create models that represent JSON objects. The resulting model is of type JsonObject . Application code can use the interface JsonArrayBuilder to create models that represent JSON arrays. The resulting model is of type JsonArray .

These object models can also be created from an input source (such as InputStream or Reader ) using the interface JsonReader . Similarly, these object models can be written to an output source (such as OutputStream or Writer ) using the class JsonWriter .

For example, let’s write code to search Facebook’s public posts using the object model API. The Facebook API gives the search results in the JSON format shown in Listing 2:

1 < 2 "data" : [ 3 < "from" : < "name" : "xxx", . >, "message" : "yyy", . >, 4 < "from" : < "name" : "ppp", . >, "message" : "qqq", . >, 5 . 6 ], 7 . 8 > 

Listing 2. JSON representation of searching Facebook public posts

We can use the object model API to get names and their public posts about the term java. In the Listing 3, lines 1 through 3 lines create JsonReader ; line 5 creates JsonObject for the results; line 7 loops over each result; and lines 8 through 11 get the name of the person who posted, get the public post, and prints them. Note that the JsonReader and other objects in this API can be used in the try -with-resources statement (which is also called automatic resource management [ARM]).

 1 URL url = new URL("https://graph.facebook.com/search?q=java&type=post"); 2 try (InputStream is = url.openStream(); 3 JsonReader rdr = Json.createReader(is)) < 4 5 JsonObject obj = rdr.readObject(); 6 JsonArray results = obj.getJsonArray("data"); 7 for (JsonObject result : results.getValuesAs(JsonObject.class)) < 8 System.out.print(result.getJsonObject("from").getString("name")); 9 System.out.print(": "); 10 System.out.println(result.getString("message", "")); 11 System.out.println("-----------"); 12 >13 > 

Listing 3. Processing Facebook posts using the object model API

The Streaming API

The streaming API is similar to the Streaming API for XML (StAX) and consists of the interfaces JsonParser and JsonGenerator . JsonParser contains methods to parse JSON data using the streaming model. JsonGenerator contains methods to write JSON data to an output source. Table 2 lists the main classes and interfaces in the streaming API.

Table 2. Main classes in the streaming API

Class or Interface Description
Json Contains static methods to create JSON parsers, generators, and their factory objects.
JsonParser Represents an event-based parser that can read JSON data from a stream.
JsonGenerator Writes JSON data to a stream one value at a time

JsonParser provides forward, read-only access to JSON data using the pull parsing programming 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.

JsonGenerator provides methods to write JSON data to a stream. The generator can be used to write name/value pairs in JSON objects and values in JSON arrays.

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 implemented using this API.

Let’s use the streaming API to do the same thing that was done with the object model API, that is, to search Facebook’s public posts about java. In Listing 4, lines 1 through 3 create a streaming parser, lines 4 through 5 get the next event, line 6 looks for the KEY_NAME event, lines 8 through 11 read names and print them, and lines 14 through 16 read the public posts and print them. The use of streaming API provides an efficient way to access names and their public posts when compared to the same task using the object model API.

 1 URL url = new URL("https://graph.facebook.com/search?q=java&type=post"); 2 try (InputStream is = url.openStream(); 3 JsonParser parser = Json.createParser(is)) < 4 while (parser.hasNext()) < 5 Event e = parser.next(); 6 if (e == Event.KEY_NAME) < 7 switch (parser.getString()) < 8 case "name": 9 parser.next(); 10 System.out.print(parser.getString()); 11 System.out.print(": "); 12 break; 13 case "message": 14 parser.next(); 15 System.out.println(parser.getString()); 16 System.out.println("---------"); 17 break; 18 >19 > 20 > 21 > 

Listing 4. Processing Facebook posts using the streaming API

Conclusion

The Java API for JSON Processing provides the following capabilities:

  • Parsing input streams into immutable objects or event streams
  • Writing event streams or immutable objects to output streams
  • Programmatically navigating immutable objects
  • Programmatically building immutable objects with builders

The API becomes a base for building data binding, transformation, querying, or other manipulation APIs. JAX-RS 2.0 provides native integration for the Java API for JSON Processing.

See Also

About the Author

Jitendra Kotamraju, a principal member of the technical staff at Oracle, is the JSON Processing specification lead and one of the key engineers behind GlassFish. Before leading the JSON Processing project, he was in charge of both the specification and implementation of JAX-WS 2.2.

Join the Conversation

Join the Java community conversation on Facebook, Twitter, and the Oracle Java Blog!

Источник

How to work with JSON easily in Java

Carlos Delgado

Learn how to create and manipulate JSON strings in Java.

How to work with JSON easily in Java

JSON is a light-weight, language independent, data interchange format that is being used nowadays on every single web API available out there. If you are willing to manipulate this kind of data in a Java environment, we’ll explain you how to achieve it easily using the org.json package.

1. Include org.json package

Java by default doesn’t offer any integrated functionality to parse or create JSON unlike PHP or other languages, instead you will need to rely on a third party library/package. In this tutorial, we’ll use the org.json. The files in this package implement JSON encoders/decoders in Java. It also includes the capability to convert between JSON and XML, HTTP headers, Cookies, and CDL. This is a reference implementation. There is a large number of JSON packages in Java. Perhaps someday the Java community will standardize on one. Until then, we recommend you to use the org.json package that makes the things pretty easy.

You can either download the jar file of the package from the maven repository and include it manually in your project or if your project is maven based, you may edit the pom.xml file and add the dependency:

For more information about this package, please visit the official repository at Maven here. After including the library, you will be able to import the package with import org.json.*; in your code.

2. Using the library to manipulate JSON

As every tutorial in Our Code World, you will learn by doing and reading some examples. We’ll share with you a couple of the most used features when you work with JSON in Java:

A. Creating JSON objects

The put method of a JSONObject class allows you to define a new key with a value to the object:

package sandbox; import org.json.*; public class Sandbox < /** * Generating a JSON Object * * @param args */ public static void main(String[] args) < JSONObject myObject = new JSONObject(); // Basic strings myObject.put("name", "Carlos"); myObject.put("last_name", "Carlos"); // Primitive values myObject.put("age", new Integer(21)); myObject.put("bank_account_balance", new Double(20.2)); myObject.put("is_developer", new Boolean(true)); // Key with array double[] myList = ; myObject.put("number_list", myList); // Object inside object JSONObject subdata = new JSONObject(); myObject.put("extra_data", subdata); // Generate JSON String System.out.print(myObject); > > 

The code will print the following structure in the console of the generated JSON string:

< "number_list": [ 1.9, 2.9, 3.4, 3.5 ], "extra_data": <>, "name": "Carlos", "last_name": "Carlos", "bank_account_balance": 20.2, "age": 21, "is_developer": true >

B. Creating JSON Arrays

The put method of a JSONArray class allows you to push some value to the array:

package sandbox; import org.json.*; public class Sandbox < /** * Generating a JSON Array * * @param args */ public static void main(String[] args) < JSONArray myArray = new JSONArray(); // Push mixed values to the array myArray.put(1); myArray.put(2); myArray.put(3); myArray.put(4); myArray.put(new Boolean(true)); myArray.put(new Boolean(false)); myArray.put("Some String Value"); // Generate JSON String System.out.print(myArray); >> 

The code will print the following structure in the console of the generated JSON string:

[1,2,3,4,true,false,"Some String Value"]

C. Parsing JSON strings

If you are willing to convert a JSON string in your code (converting it to arrays or objects), just provide the string as first argument of the constructor of the class according to the type, for example, if you want to convert a string of JSONArray:

package sandbox; import org.json.*; public class Sandbox < /** * Parsing a JSONArray string * * @param args */ public static void main(String[] args) < JSONArray myJson = new JSONArray("[123,<\"1\":<\"2\":<\"3\":<\"4\":[5,<\"6\":7>]>>>>]"); // Print first value of the array System.out.print(myJson.get(0)); // Print second value of the array System.out.print(myJson.get(1)); > > 

Or if you want to convert a string to a JSONObject:

package sandbox; import org.json.*; public class Sandbox < /** * Parsing a JSONObject string * * @param args */ public static void main(String[] args) < JSONObject myJson = new JSONObject("< \"number_list\": [ 1.9, 2.9, 3.4, 3.5 ], \"extra_data\": <>, \"name\": \"Carlos\", \"last_name\": \"Carlos\", \"bank_account_balance\": 20.2, \"age\": 21, \"is_developer\": true >"); // Get some keys from the JSON Object System.out.print(myJson.get("name")); // Carlos System.out.print(myJson.get("age")); // 21 > > 

Источник

Оцените статью