About Blaise Doughan

Team lead for the TopLink/EclipseLink JAXB & SDO implementations, and the Oracle representative on those specifications.

Java API for JSON Processing (JSR-353) – Stream APIs

Java will soon have a standard set of APIs for processing JSON as part of Java EE 7. This standard is being defined as JSR 353 – Java API for JSON Processing (JSON-P) and it is currently at the Final Approval Ballot. JSON-P offers both object oriented and stream based approaches, in this post I will introduce the stream APIs. You can get JSON-P reference implementation from the link below:

 
 
 

JsonGenerator (javax.json.stream)

JsonGenerator makes it very easy to create JSON. With its fluent API the code to produce the JSON very closely resembles the resulting JSON.

package blog.jsonp;
 
import java.util.*;
import javax.json.Json;
import javax.json.stream.*;
 
public class GeneratorDemo {
 
    public static void main(String[] args) {
        Map<String, Object> properties = new HashMap<String, Object>(1);
        properties.put(JsonGenerator.PRETTY_PRINTING, true);
        JsonGeneratorFactory jgf = Json.createGeneratorFactory(properties);
        JsonGenerator jg = jgf.createGenerator(System.out);
         
        jg.writeStartObject()                    // {
            .write("name", "Jane Doe")           //    "name":"Jane Doe",
            .writeStartObject("address")         //    "address":{
                .write("type", 1)                //        "type":1,
                .write("street", "1 A Street")   //        "street":"1 A Street",
                .writeNull("city")               //        "city":null,
                .write("verified", false)        //        "verified":false
            .writeEnd()                          //    },
            .writeStartArray("phone-numbers")    //    "phone-numbers":[
                .writeStartObject()              //        {
                    .write("number", "555-1111") //            "number":"555-1111",
                    .write("extension", "123")   //            "extension":"123"
                .writeEnd()                      //        },
                .writeStartObject()              //        {
                    .write("number", "555-2222") //            "number":"555-2222",
                    .writeNull("extension")      //            "extension":null
                .writeEnd()                      //        }
            .writeEnd()                          //    ]
        .writeEnd()                              // }
        .close();
    }
 
}

Output

Below is the output from running the GeneratorDemo.

{
    "name":"Jane Doe",
    "address":{
        "type":1,
        "street":"1 A Street",
        "city":null,
        "verified":false
    },
    "phone-numbers":[
        {
            "number":"555-1111",
            "extension":"123"
        },
        {
            "number":"555-2222",
            "extension":null
        }
    ]
}

JsonParser (javax.json.stream)

Using JsonParser we will parse the output of the previous example to get the address information. JSON parser provides a depth first traversal of events corresponding to the JSON structure. Different data can be obtained from the JsonParser depending on the type of the event.

package blog.jsonp;
 
import java.io.FileInputStream;
import javax.json.Json;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParser.Event;
 
public class ParserDemo {
 
    public static void main(String[] args) throws Exception  {
        try (FileInputStream json = new FileInputStream("src/blog/jsonp/input.json")) {
            JsonParser jr = Json.createParser(json);
            Event event = null;
     
            // Advance to "address" key
            while(jr.hasNext()) {
                event = jr.next();
                if(event == Event.KEY_NAME && "address".equals(jr.getString())) {
                    event = jr.next();
                    break;
                }
            }
     
            // Output contents of "address" object
            while(event != Event.END_OBJECT) {
                switch(event) {
                    case KEY_NAME: {
                        System.out.print(jr.getString());
                        System.out.print(" = ");
                        break;
                    }
                    case VALUE_FALSE: {
                        System.out.println(false);
                        break;
                    }
                    case VALUE_NULL: {
                        System.out.println("null");
                        break;
                    }
                    case VALUE_NUMBER: {
                        if(jr.isIntegralNumber()) {
                            System.out.println(jr.getInt());
                        } else {
                            System.out.println(jr.getBigDecimal());
                        }
                       break;
                    }
                    case VALUE_STRING: {
                        System.out.println(jr.getString());
                        break;
                    }
                    case VALUE_TRUE: {
                        System.out.println(true);
                        break;
                    }
                    default: {
                    }
                }
                event = jr.next();
            }
        }
    }
 
}

Output

Below is the output from running the ParserDemo.

type = 1
street = 1 A Street
city = null
verified = false

MOXy and the Java API for JSON Processing (JSR-353)

Mapping your JSON to domain objects is still the easiest way to interact with JSON. Now that JSR-353 is finalizing we will integrating it into MOXy’s JSON-binding. You can track our progress on this using the following link:

 

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

2 Responses to "Java API for JSON Processing (JSR-353) – Stream APIs"

  1. Sergey Chunayev says:

    And again Java is the leader in verbosity. I love Java and JVM, but more and more I ask myself “What they were thinking of developing their API?”. If we are talking about fluent API, and the key word here is FLUENT, why make it so verbose? Doesn’t the code below look better?

    jg.object()
    .put(“name”, “Jane Doe”)
    .object(“address”)
    .put(“type”, 1)
    .put(“street”, “1 A Street”)
    .put(“city”, null)
    .put(“verified”)
    .end()
    .array(“phone-numbers”)
    .object()
    .put(“number”, “555-1111″)
    .put(“extension”, “123″)
    .end()
    .object()
    .put(“number”, “555-222″)
    .end()
    .end()
    .end()

    I know one can object saying “C’mon, it’s just a method name, once you know it it’s simple”. But one unnecessarily long name here, another there and you realize that in order to read what some code does you have to read 3 times more of its meta-data.

    • Blaise Doughan says:

      With your proposal the number of lines of code remains the same, your point is the method names are unnecessarily long. This is a hard balance to strike. I find the current method names work well without having to read their Javadoc. I’m not sure what I would think your method “end” would do if I saw it come up as a possible method as part of code completion. These APIs are also similar to the StAX (JSR-173) APIs so there is less of a learning curve for XML developers who want to do JSON processing.

      One thing to remember is that all the Java SE and Java EE standards are developed in the open. If you have input on what you think APIs should look like, it is most effective to raise those points while the specifications are still in development.

Leave a Reply


eight + = 13



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books