SlideShare a Scribd company logo
1 of 29
WebSocket & JSON Java
APIs Hackday
By Somay Nakhal @SomayNakhal
   David Illsley @davidillsley




                                 1
Hackday ?



∀   Adapt A JSR programme
∀   Explore new APIs
∀   JSR 353 JSON Processing API
∀   JSR 356 WebSockets API
∀   Provide feedback




                                  2
WebSocket and Java




                3
∀   Interactive web application
∀   HTTP is half-duplex
∀   Polling
∀   Long Polling
∀   Comet/Ajax
∀   Complex, Inefficient, Wasteful




                                     4
Enter WebSocket Protocol

∀   TCP based, bi-directional, full-duplex messaging
∀   Part of HTML5
∀   IETF-defined Protocol: RFC 6455
∀   W3C defined JavaScript API
∀   Uses HTTP upgrade handshake
∀   Supports HTTP proxies, filtering, authentication and intermediaries




                                                               5
How does it work?

∀   Establish connection (Single TCP connection)
∀   Send messages in both direction (Bi-directional)
∀   Send messages independent of each other (Full Duplex)
∀   End connection




                                                            6
Browser Support




                                7
caniuse.com
WebSocket API (JavaScript)


var websocket = new WebSocket("ws://www.host.com/path");
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) }; }

function onMessage(evt) { alert( evt.data); }
function onError(evt) { alert( evt.data); }

websocket.send("client to server");




                                                           8
JSR 356
Java API for WebSocket




                         9
JSR 356 Java API for WebSocket

∀   Client and Server WebSocket protocol APIs in Java
∀   Integration with Java EE Web container
∀   Reference Implementation:
∀   – http://java.net/projects/tyrus
∀   – Bundled in latest Glassfish 4 builds




                                                        10
Terminology


∀   Endpoint: Client or server
∀   Connection: Network connection between two endpoints
∀   Peer: Other endpoint of the connection
∀   Session: represents a sequence of websocket interactions
    between and end point and a peer




                                                               11
Annotations

∀ @WebSocketEndpoint
  – Class level annotation for websocket server endpoint
∀ @WebSocketClient
  – Class level annotation for websocket client endpoint
∀ @WebSocketOpen
  – Method level annotation signifies a method to be called whenever a new
    client connects to this endpoint
∀ @WebSocketClose
  – Method level annotation signifies a method to be called whenever a new
    client is about to disconnects from this endpoint
∀ @WebSocketMessage
  – Method level annotation signifies a method to be called whenever an
    incoming message is received



                                                                 12
Some Code!


@WebSocketEndpoint("/hello-world")
public class HelloWorld {
     @WebSocketMessage
     public String sayHello(String name) {
          return "Hello " + name;
     }
}




                                      13
More Code!

@WebSocketEndpoint("/hello-world")
public class HelloWorld {
        private Set<Session> peers = Collections.synchronizedSet(…)

       @WebSocketOpen
       public void onOpen (Session peer) {
               peers.add(peer);
       }


       private void sendMessageToPeer(String message, Session peer) {
               peer.getRemote().sendString(s);
       }

}




                                                           14
JSON and Java




                15
In the beginning...

There was XML
... and the DOM... and SAX...


Then, after much gnashing of teeth, there was JSON


 { "message" : "Hello World!" }

                                               More at json.org and wikipedia




                                                                16
tumbleweed...




                17
Not Quite



"The Software shall be used for Good, not Evil."
From: http://www.json.org/license.html




                                                   18
And many more...
•   org.json.me.
•   Jackson JSON Processor.
•   Json-lib.
•   JSON Tools.
•   Stringtree.
•   SOJO.
•   Jettison.
•   json-taglib.
•   XStream.
•   Flexjson.
•   JON tools.
•   Argo.
•   jsonij.
•   fastjson.
•   mjson.
•   jjson.
•   json-simple.
•   json-io.
•   JsonMarshaller.
•   google-gson.
•   Json-smart.
•   FOSS Nova JSON.

                              (list from json.org)

                                   19
Fast-forward to December 2011

JSR 353: JavaTM API for JSON Processing

"JSON(JavaScript Object Notation) is a lightweight data-interchange format.
   Many popular web services use JSON format for invoking and returning the
   data. Currently Java applications use different implementation libraries to
   produce/consume JSON from the web services. Hence, there is a need to
   standardize a Java API for JSON so that applications that use JSON need
   not bundle the implementation libraries but use the API. Applications will be
   smaller in size and portable."


                                               http://jcp.org/en/jsr/detail?id=353




                                                                       20
Goals/Non Goals

"The goal of this specification is to develop such APIs to:
* Produce and consume JSON text in a streaming fashion(similar to StAX API
    for XML)
* Build a Java object model for JSON text using API classes(similar to DOM
   API for XML)
Non-goals of this specification include:
* Binding of JSON text to Java objects and vice versa."


"This JSR is targeted for Java SE 6 or higher and Java EE 7 or higher
   platforms."


                                                http://jcp.org/en/jsr/detail?id=353



                                                                        21
Fast-forward to February 2013

Pretty much done


Just finished the formal public review phase


Looking for final feedback from JUGs
... and to get the word out about what's coming




                                                  22
Some code...
JsonGenerator generator = Json.createGenerator(System.out)
// or generator = Json.createGenerator(servletResponse.getWriter())
generator
        .writeStartObject()
            .write("firstName", "John")
            .write("lastName", "Smith")
            .write("age", 25)
            .writeStartObject("address")
                .write("streetAddress", "21 2nd Street")
                .write("city", "New York")
                .write("state", "NY")
                .write("postalCode", "10021")
            .writeEnd()
            .writeStartArray("phoneNumber")
                .writeStartObject()
                     .write("type", "home")
                     .write("number", "212 555-1234")
                .writeEnd()
                .writeStartObject()
                     .write("type", "fax")
                     .write("number", "646 555-4567")
                .writeEnd()
            .writeEnd()
        .writeEnd();
    generator.close();
                                                                      23
Produces
{
        "firstName": "John", "lastName": "Smith", "age": 25,
        "address" : {
            "streetAddress": "21 2nd Street",
            "city": "New York",
            "state": "NY",
            "postalCode": "10021"
        },
        "phoneNumber": [
            {"type": "home", "number": "212 555-1234"},
            {"type": "fax", "number": "646 555-4567"}
         ]
    }


                                        (JavaDoc - JsonGenerator) http://bit.ly/11CwMde




                                                                          24
Or to build an object model...
JsonObject value = Json.createObjectBuilder()
        .add("firstName", "John")
        .add("lastName", "Smith")
        .add("age", 25)
        .add("address", Json.createObjectBuilder()
            .add("streetAddress", "21 2nd Street")
            .add("city", "New York")
            .add("state", "NY")
            .add("postalCode", "10021"))
        .add("phoneNumber", Json.createArrayBuilder()
            .add(Json.createObjectBuilder()
                .add("type", "home")
                .add("number", "212 555-1234"))
            .add(Json.createObjectBuilder()
                .add("type", "fax")
                .add("number", "646 555-4567")))
        .build();
// or from a stream..
JsonObject value2 = Json.createReader(inputStream).readObject();

                                             (JavaDoc - JsonObject) bit.ly/11CwMde
                                                                      25
And to read things from it...
int age = value2.getIntValue("age", 18);


JsonObject address = value2.getValue("address", JsonObject.class);
String city = "London";
if(address != null){
    city = address.getStringValue("city", "London");
}


JsonArray phoneNumbers = value2.getValue("phoneNumber", JsonArray.class);
if(phoneNumbers != null){
    for(JsonValue val: value2){
        if(val instanceof JsonObject){
            JsonObject jo = (JsonObject)val;
            System.out.println(jo.getStringValue("number","Number Missing");
        }
    }
}
                                                                       26
And a low-level event API


Event event = parser.next(); // START_OBJECT
   event = parser.next();       // KEY_NAME
   event = parser.next();       // VALUE_STRING
   parser.getString();          // "John"
                                             (JavaDoc - JsonParser) bit.ly/VzGWEr




                                                                    27
JSON Hacks/Workshop

Latest version of the library not in Glassfish yet, so a small standalone
   maven project


             https://github.com/davidillsley/json-workshop


Includes tests for some uncompleted code operating on stored JSON..
   see the README for more.




                                                                28
29

More Related Content

What's hot

Node.js and angular js
Node.js and angular jsNode.js and angular js
Node.js and angular jsHyungKuIm
 
Codes
CodesCodes
CodesOSit3
 
Websockets, Ruby y Pusher Webprendedor 2010
Websockets, Ruby y Pusher Webprendedor 2010Websockets, Ruby y Pusher Webprendedor 2010
Websockets, Ruby y Pusher Webprendedor 2010Ismael Celis
 
The Ring programming language version 1.8 book - Part 49 of 202
The Ring programming language version 1.8 book - Part 49 of 202The Ring programming language version 1.8 book - Part 49 of 202
The Ring programming language version 1.8 book - Part 49 of 202Mahmoud Samir Fayed
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance TuningPuneet Behl
 
Map/Confused? A practical approach to Map/Reduce with MongoDB
Map/Confused? A practical approach to Map/Reduce with MongoDBMap/Confused? A practical approach to Map/Reduce with MongoDB
Map/Confused? A practical approach to Map/Reduce with MongoDBUwe Printz
 
Better Web Clients with Mantle and AFNetworking
Better Web Clients with Mantle and AFNetworkingBetter Web Clients with Mantle and AFNetworking
Better Web Clients with Mantle and AFNetworkingGuillermo Gonzalez
 
Code Samples &amp; Screenshots
Code Samples &amp; ScreenshotsCode Samples &amp; Screenshots
Code Samples &amp; ScreenshotsNii Amah Hesse
 
Back to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB ApplicationBack to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB ApplicationMongoDB
 
Back to Basics Webinar 3 - Thinking in Documents
Back to Basics Webinar 3 - Thinking in DocumentsBack to Basics Webinar 3 - Thinking in Documents
Back to Basics Webinar 3 - Thinking in DocumentsJoe Drumgoole
 
25 Million Flows Later – Large-scale Detection of DOM-based XSS
25 Million Flows Later – Large-scale Detection of DOM-based XSS25 Million Flows Later – Large-scale Detection of DOM-based XSS
25 Million Flows Later – Large-scale Detection of DOM-based XSSBen Stock
 
MongoDB Performance Debugging
MongoDB Performance DebuggingMongoDB Performance Debugging
MongoDB Performance DebuggingMongoDB
 
The Ring programming language version 1.7 book - Part 47 of 196
The Ring programming language version 1.7 book - Part 47 of 196The Ring programming language version 1.7 book - Part 47 of 196
The Ring programming language version 1.7 book - Part 47 of 196Mahmoud Samir Fayed
 
Blockchain: Developer Perspective
Blockchain: Developer PerspectiveBlockchain: Developer Perspective
Blockchain: Developer PerspectiveArtur Skowroński
 
Back to Basics Webinar 1 - Introduction to NoSQL
Back to Basics Webinar 1 - Introduction to NoSQLBack to Basics Webinar 1 - Introduction to NoSQL
Back to Basics Webinar 1 - Introduction to NoSQLJoe Drumgoole
 
Mongo DB schema design patterns
Mongo DB schema design patternsMongo DB schema design patterns
Mongo DB schema design patternsjoergreichert
 
Redis data modeling examples
Redis data modeling examplesRedis data modeling examples
Redis data modeling examplesTerry Cho
 

What's hot (20)

Node.js and angular js
Node.js and angular jsNode.js and angular js
Node.js and angular js
 
Codes
CodesCodes
Codes
 
Websockets, Ruby y Pusher Webprendedor 2010
Websockets, Ruby y Pusher Webprendedor 2010Websockets, Ruby y Pusher Webprendedor 2010
Websockets, Ruby y Pusher Webprendedor 2010
 
The Ring programming language version 1.8 book - Part 49 of 202
The Ring programming language version 1.8 book - Part 49 of 202The Ring programming language version 1.8 book - Part 49 of 202
The Ring programming language version 1.8 book - Part 49 of 202
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance Tuning
 
Map/Confused? A practical approach to Map/Reduce with MongoDB
Map/Confused? A practical approach to Map/Reduce with MongoDBMap/Confused? A practical approach to Map/Reduce with MongoDB
Map/Confused? A practical approach to Map/Reduce with MongoDB
 
Better Web Clients with Mantle and AFNetworking
Better Web Clients with Mantle and AFNetworkingBetter Web Clients with Mantle and AFNetworking
Better Web Clients with Mantle and AFNetworking
 
Code Samples &amp; Screenshots
Code Samples &amp; ScreenshotsCode Samples &amp; Screenshots
Code Samples &amp; Screenshots
 
Mongo db presentation
Mongo db presentationMongo db presentation
Mongo db presentation
 
Back to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB ApplicationBack to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB Application
 
Back to Basics Webinar 3 - Thinking in Documents
Back to Basics Webinar 3 - Thinking in DocumentsBack to Basics Webinar 3 - Thinking in Documents
Back to Basics Webinar 3 - Thinking in Documents
 
25 Million Flows Later – Large-scale Detection of DOM-based XSS
25 Million Flows Later – Large-scale Detection of DOM-based XSS25 Million Flows Later – Large-scale Detection of DOM-based XSS
25 Million Flows Later – Large-scale Detection of DOM-based XSS
 
Indexing
IndexingIndexing
Indexing
 
MongoDB Performance Debugging
MongoDB Performance DebuggingMongoDB Performance Debugging
MongoDB Performance Debugging
 
Couchdb w Ruby'm
Couchdb w Ruby'mCouchdb w Ruby'm
Couchdb w Ruby'm
 
The Ring programming language version 1.7 book - Part 47 of 196
The Ring programming language version 1.7 book - Part 47 of 196The Ring programming language version 1.7 book - Part 47 of 196
The Ring programming language version 1.7 book - Part 47 of 196
 
Blockchain: Developer Perspective
Blockchain: Developer PerspectiveBlockchain: Developer Perspective
Blockchain: Developer Perspective
 
Back to Basics Webinar 1 - Introduction to NoSQL
Back to Basics Webinar 1 - Introduction to NoSQLBack to Basics Webinar 1 - Introduction to NoSQL
Back to Basics Webinar 1 - Introduction to NoSQL
 
Mongo DB schema design patterns
Mongo DB schema design patternsMongo DB schema design patterns
Mongo DB schema design patterns
 
Redis data modeling examples
Redis data modeling examplesRedis data modeling examples
Redis data modeling examples
 

Similar to WebSocket JSON Hackday

Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.Mike Brevoort
 
JSON Fuzzing: New approach to old problems
JSON Fuzzing: New  approach to old problemsJSON Fuzzing: New  approach to old problems
JSON Fuzzing: New approach to old problemstitanlambda
 
Introduction to JSON & AJAX
Introduction to JSON & AJAXIntroduction to JSON & AJAX
Introduction to JSON & AJAXRaveendra R
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineRicardo Silva
 
Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Ismael Celis
 
Native Phone Development 101
Native Phone Development 101Native Phone Development 101
Native Phone Development 101Sasmito Adibowo
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...GITS Indonesia
 
Hybrid apps - Your own mini Cordova
Hybrid apps - Your own mini CordovaHybrid apps - Your own mini Cordova
Hybrid apps - Your own mini CordovaAyman Mahfouz
 
SockJS Intro
SockJS IntroSockJS Intro
SockJS IntroNgoc Dao
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.jsYoann Gotthilf
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSocketsGonzalo Ayuso
 
Data Types/Structures in DivConq
Data Types/Structures in DivConqData Types/Structures in DivConq
Data Types/Structures in DivConqeTimeline, LLC
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryAlexandre Morgaut
 
Con fess 2013-sse-websockets-json-bhakti
Con fess 2013-sse-websockets-json-bhaktiCon fess 2013-sse-websockets-json-bhakti
Con fess 2013-sse-websockets-json-bhaktiBhakti Mehta
 
Intravert Server side processing for Cassandra
Intravert Server side processing for CassandraIntravert Server side processing for Cassandra
Intravert Server side processing for CassandraEdward Capriolo
 

Similar to WebSocket JSON Hackday (20)

Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
 
JSON Fuzzing: New approach to old problems
JSON Fuzzing: New  approach to old problemsJSON Fuzzing: New  approach to old problems
JSON Fuzzing: New approach to old problems
 
Json at work overview and ecosystem-v2.0
Json at work   overview and ecosystem-v2.0Json at work   overview and ecosystem-v2.0
Json at work overview and ecosystem-v2.0
 
Introduction to JSON & AJAX
Introduction to JSON & AJAXIntroduction to JSON & AJAX
Introduction to JSON & AJAX
 
Os Pruett
Os PruettOs Pruett
Os Pruett
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010
 
Java EE 7 overview
Java EE 7 overviewJava EE 7 overview
Java EE 7 overview
 
Native Phone Development 101
Native Phone Development 101Native Phone Development 101
Native Phone Development 101
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
 
Hybrid apps - Your own mini Cordova
Hybrid apps - Your own mini CordovaHybrid apps - Your own mini Cordova
Hybrid apps - Your own mini Cordova
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
SockJS Intro
SockJS IntroSockJS Intro
SockJS Intro
 
NodeJS
NodeJSNodeJS
NodeJS
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.js
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
Data Types/Structures in DivConq
Data Types/Structures in DivConqData Types/Structures in DivConq
Data Types/Structures in DivConq
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love Story
 
Con fess 2013-sse-websockets-json-bhakti
Con fess 2013-sse-websockets-json-bhaktiCon fess 2013-sse-websockets-json-bhakti
Con fess 2013-sse-websockets-json-bhakti
 
Intravert Server side processing for Cassandra
Intravert Server side processing for CassandraIntravert Server side processing for Cassandra
Intravert Server side processing for Cassandra
 

WebSocket JSON Hackday

  • 1. WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley 1
  • 2. Hackday ? ∀ Adapt A JSR programme ∀ Explore new APIs ∀ JSR 353 JSON Processing API ∀ JSR 356 WebSockets API ∀ Provide feedback 2
  • 4. Interactive web application ∀ HTTP is half-duplex ∀ Polling ∀ Long Polling ∀ Comet/Ajax ∀ Complex, Inefficient, Wasteful 4
  • 5. Enter WebSocket Protocol ∀ TCP based, bi-directional, full-duplex messaging ∀ Part of HTML5 ∀ IETF-defined Protocol: RFC 6455 ∀ W3C defined JavaScript API ∀ Uses HTTP upgrade handshake ∀ Supports HTTP proxies, filtering, authentication and intermediaries 5
  • 6. How does it work? ∀ Establish connection (Single TCP connection) ∀ Send messages in both direction (Bi-directional) ∀ Send messages independent of each other (Full Duplex) ∀ End connection 6
  • 7. Browser Support 7 caniuse.com
  • 8. WebSocket API (JavaScript) var websocket = new WebSocket("ws://www.host.com/path"); websocket.onopen = function(evt) { onOpen(evt) }; websocket.onclose = function(evt) { onClose(evt) }; websocket.onmessage = function(evt) { onMessage(evt) }; websocket.onerror = function(evt) { onError(evt) }; } function onMessage(evt) { alert( evt.data); } function onError(evt) { alert( evt.data); } websocket.send("client to server"); 8
  • 9. JSR 356 Java API for WebSocket 9
  • 10. JSR 356 Java API for WebSocket ∀ Client and Server WebSocket protocol APIs in Java ∀ Integration with Java EE Web container ∀ Reference Implementation: ∀ – http://java.net/projects/tyrus ∀ – Bundled in latest Glassfish 4 builds 10
  • 11. Terminology ∀ Endpoint: Client or server ∀ Connection: Network connection between two endpoints ∀ Peer: Other endpoint of the connection ∀ Session: represents a sequence of websocket interactions between and end point and a peer 11
  • 12. Annotations ∀ @WebSocketEndpoint – Class level annotation for websocket server endpoint ∀ @WebSocketClient – Class level annotation for websocket client endpoint ∀ @WebSocketOpen – Method level annotation signifies a method to be called whenever a new client connects to this endpoint ∀ @WebSocketClose – Method level annotation signifies a method to be called whenever a new client is about to disconnects from this endpoint ∀ @WebSocketMessage – Method level annotation signifies a method to be called whenever an incoming message is received 12
  • 13. Some Code! @WebSocketEndpoint("/hello-world") public class HelloWorld { @WebSocketMessage public String sayHello(String name) { return "Hello " + name; } } 13
  • 14. More Code! @WebSocketEndpoint("/hello-world") public class HelloWorld { private Set<Session> peers = Collections.synchronizedSet(…) @WebSocketOpen public void onOpen (Session peer) { peers.add(peer); } private void sendMessageToPeer(String message, Session peer) { peer.getRemote().sendString(s); } } 14
  • 16. In the beginning... There was XML ... and the DOM... and SAX... Then, after much gnashing of teeth, there was JSON { "message" : "Hello World!" } More at json.org and wikipedia 16
  • 18. Not Quite "The Software shall be used for Good, not Evil." From: http://www.json.org/license.html 18
  • 19. And many more... • org.json.me. • Jackson JSON Processor. • Json-lib. • JSON Tools. • Stringtree. • SOJO. • Jettison. • json-taglib. • XStream. • Flexjson. • JON tools. • Argo. • jsonij. • fastjson. • mjson. • jjson. • json-simple. • json-io. • JsonMarshaller. • google-gson. • Json-smart. • FOSS Nova JSON. (list from json.org) 19
  • 20. Fast-forward to December 2011 JSR 353: JavaTM API for JSON Processing "JSON(JavaScript Object Notation) is a lightweight data-interchange format. Many popular web services use JSON format for invoking and returning the data. Currently Java applications use different implementation libraries to produce/consume JSON from the web services. Hence, there is a need to standardize a Java API for JSON so that applications that use JSON need not bundle the implementation libraries but use the API. Applications will be smaller in size and portable." http://jcp.org/en/jsr/detail?id=353 20
  • 21. Goals/Non Goals "The goal of this specification is to develop such APIs to: * Produce and consume JSON text in a streaming fashion(similar to StAX API for XML) * Build a Java object model for JSON text using API classes(similar to DOM API for XML) Non-goals of this specification include: * Binding of JSON text to Java objects and vice versa." "This JSR is targeted for Java SE 6 or higher and Java EE 7 or higher platforms." http://jcp.org/en/jsr/detail?id=353 21
  • 22. Fast-forward to February 2013 Pretty much done Just finished the formal public review phase Looking for final feedback from JUGs ... and to get the word out about what's coming 22
  • 23. Some code... JsonGenerator generator = Json.createGenerator(System.out) // or generator = Json.createGenerator(servletResponse.getWriter()) generator .writeStartObject() .write("firstName", "John") .write("lastName", "Smith") .write("age", 25) .writeStartObject("address") .write("streetAddress", "21 2nd Street") .write("city", "New York") .write("state", "NY") .write("postalCode", "10021") .writeEnd() .writeStartArray("phoneNumber") .writeStartObject() .write("type", "home") .write("number", "212 555-1234") .writeEnd() .writeStartObject() .write("type", "fax") .write("number", "646 555-4567") .writeEnd() .writeEnd() .writeEnd(); generator.close(); 23
  • 24. Produces { "firstName": "John", "lastName": "Smith", "age": 25, "address" : { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021" }, "phoneNumber": [ {"type": "home", "number": "212 555-1234"}, {"type": "fax", "number": "646 555-4567"} ] } (JavaDoc - JsonGenerator) http://bit.ly/11CwMde 24
  • 25. Or to build an object model... JsonObject value = Json.createObjectBuilder() .add("firstName", "John") .add("lastName", "Smith") .add("age", 25) .add("address", Json.createObjectBuilder() .add("streetAddress", "21 2nd Street") .add("city", "New York") .add("state", "NY") .add("postalCode", "10021")) .add("phoneNumber", Json.createArrayBuilder() .add(Json.createObjectBuilder() .add("type", "home") .add("number", "212 555-1234")) .add(Json.createObjectBuilder() .add("type", "fax") .add("number", "646 555-4567"))) .build(); // or from a stream.. JsonObject value2 = Json.createReader(inputStream).readObject(); (JavaDoc - JsonObject) bit.ly/11CwMde 25
  • 26. And to read things from it... int age = value2.getIntValue("age", 18); JsonObject address = value2.getValue("address", JsonObject.class); String city = "London"; if(address != null){ city = address.getStringValue("city", "London"); } JsonArray phoneNumbers = value2.getValue("phoneNumber", JsonArray.class); if(phoneNumbers != null){ for(JsonValue val: value2){ if(val instanceof JsonObject){ JsonObject jo = (JsonObject)val; System.out.println(jo.getStringValue("number","Number Missing"); } } } 26
  • 27. And a low-level event API Event event = parser.next(); // START_OBJECT event = parser.next(); // KEY_NAME event = parser.next(); // VALUE_STRING parser.getString(); // "John" (JavaDoc - JsonParser) bit.ly/VzGWEr 27
  • 28. JSON Hacks/Workshop Latest version of the library not in Glassfish yet, so a small standalone maven project https://github.com/davidillsley/json-workshop Includes tests for some uncompleted code operating on stored JSON.. see the README for more. 28
  • 29. 29