json support in java ee 8

85
Copyright © 2016, Oracle and/or its affiliates. All rights rese JSON support in Java EE 8 Dmitry Kornilov JSONB/P Specification Lead @m0mus Werner Keil JSON-P EG Member @wernerkeil November 15, 2016

Upload: dmitry-kornilov

Post on 08-Jan-2017

237 views

Category:

Internet


2 download

TRANSCRIPT

Page 1: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

JSON support in Java EE 8

Dmitry KornilovJSONB/P Specification Lead@m0mus

Werner KeilJSON-P EG Member@wernerkeil

November 15, 2016

Page 2: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 2

Safe Harbor StatementThe following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.

Page 3: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 3

Werner Keil

• Consultant – Coach• Creative Cosmopolitan• Open Source Evangelist• Software Architect• Spec Lead – JSR363• Individual JCP Executive Committee

Member

Page 4: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 4

Dmitry Kornilov

• Software Developer @ Oracle• Hardcore Gamer• JSON-B (JSR-367) spec lead• JSON-P (JSR-374) spec lead• Outstanding Spec Lead 2016• EclipseLink project committer

Page 5: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 5

Program Agenda

Introduction

JSON Processing

JSON Binding

Q & A

1

2

3

5

Page 6: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 6

Introduction

Page 7: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 7

What is JSON???

Page 8: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 8

This is Jason

Page 9: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 9

This is also Jason

Page 10: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 10

This is JSON-B

Page 11: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 11

What is JSON?• JavaScript Object Notation• Subset of JavaScript• Lightweight data-interchange format• Object, Array, Value

{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

Page 12: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 12

JSON Support in Java EE 8• JSON Processing API– Standard API to parse, generate, transform, query JSON–Object Model and Streaming API• similar to DOM and StAX

• JSON Binding API– Binding JSON documents to Java objects• similar to JAXB

Page 13: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 13

JSON Processing

Page 14: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 14

JSON-P• Streaming API– JsonParser– JsonGenerator

• Object model API– JsonReader– JsonWriter– JsonPointer– JsonPatch– JsonMergePatch

Page 15: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 15

JsonParser• JsonParser– Parses JSON in a streaming way from input sources– Similar to StAX’s XMLStreamReader, a pull parser

• Created using:• Json.createParser(…), Json.createParserFactory().createParser(…)

• Optionally, configured with features• Parser state events: – START_ARRAY, START_OBJECT, KEY_NAME, VALUE_STRING, VALUE_NUMBER,

VALUE_TRUE, VALUE_FALSE, VALUE_NULL, END_OBJECT, END_ARRAY

Page 16: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 16

JsonParser{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

Page 17: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 17

JsonParserSTART_OBJECT{

"name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

Page 18: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 18

JsonParserSTART_OBJECTKEY_NAME

{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

Page 19: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 19

JsonParserSTART_OBJECTKEY_NAMEVALUE_STRING

{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

Page 20: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 20

JsonParserSTART_OBJECTKEY_NAMEVALUE_STRINGKEY_NAME

{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

Page 21: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 21

JsonParserSTART_OBJECTKEY_NAMEVALUE_STRINGKEY_NAMEVALUE_NUMBER

{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

Page 22: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 22

JsonParserSTART_OBJECTKEY_NAMEVALUE_STRINGKEY_NAMEVALUE_NUMBERKEY_NAME

{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

Page 23: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 23

JsonParserSTART_OBJECTKEY_NAMEVALUE_STRINGKEY_NAMEVALUE_NUMBERKEY_NAMESTART_ARRAY

{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

Page 24: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 24

JsonParserSTART_OBJECTKEY_NAMEVALUE_STRINGKEY_NAMEVALUE_NUMBERKEY_NAMESTART_ARRAYSTART_OBJECT

{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

Page 25: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 25

JsonParserSTART_OBJECTKEY_NAMEVALUE_STRINGKEY_NAMEVALUE_NUMBERKEY_NAMESTART_ARRAYSTART_OBJECTKEY_NAME, KEY_STRING

{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

Page 26: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 26

JsonParserSTART_OBJECTKEY_NAMEVALUE_STRINGKEY_NAMEVALUE_NUMBERKEY_NAMESTART_ARRAYSTART_OBJECTKEY_NAME, KEY_STRINGKEY_NAME, KEY_STRING

{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

Page 27: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 27

JsonParserSTART_OBJECTKEY_NAMEVALUE_STRINGKEY_NAMEVALUE_NUMBERKEY_NAMESTART_ARRAYSTART_OBJECTKEY_NAME, KEY_STRINGKEY_NAME, KEY_STRINGEND_OBJECT

{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

Page 28: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 28

JsonParserSTART_OBJECTKEY_NAMEVALUE_STRINGKEY_NAMEVALUE_NUMBERKEY_NAMESTART_ARRAYSTART_OBJECTKEY_NAME, KEY_STRINGKEY_NAME, KEY_STRINGEND_OBJECTEND_ARRAY

{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

Page 29: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 29

JsonParserSTART_OBJECTKEY_NAMEVALUE_STRINGKEY_NAMEVALUE_NUMBERKEY_NAMESTART_ARRAYSTART_OBJECTKEY_NAME, KEY_STRINGKEY_NAME, KEY_STRINGEND_OBJECTEND_ARRAYEND_OBJECT

{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

Page 30: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 30

JsonParser{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

JsonParser parser = Json.createParser(...);

Page 31: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 31

JsonParser{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

JsonParser parser = Json.createParser(...);Event e = parser.next(); // START_OBJECT

Page 32: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 32

JsonParser{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

JsonParser parser = Json.createParser(...);Event e = parser.next(); // START_OBJECT parser.next(); // KEY_NAME

Page 33: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 33

JsonParser{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

JsonParser parser = Json.createParser(...);Event e = parser.next(); // START_OBJECT parser.next(); // KEY_NAMEparser.getString(); // name

Page 34: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 34

JsonParser{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

JsonParser parser = Json.createParser(...);Event e = parser.next(); // START_OBJECT parser.next(); // KEY_NAMEparser.getString(); // nameparser.next(); // VALUE_STRING

Page 35: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 35

JsonParser{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

JsonParser parser = Json.createParser(...);Event e = parser.next(); // START_OBJECT parser.next(); // KEY_NAMEparser.getString(); // nameparser.next(); // VALUE_STRINGparser.getString(); // Jason Bourne

Page 36: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 36

JsonParser{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

JsonParser parser = Json.createParser(...);Event e = parser.next(); // START_OBJECT parser.next(); // KEY_NAMEparser.getString(); // nameparser.next(); // VALUE_STRINGparser.getString(); // Jason Bourneparser.next(); // KEY_NAME

Page 37: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 37

JsonParser{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

JsonParser parser = Json.createParser(...);Event e = parser.next(); // START_OBJECT parser.next(); // KEY_NAMEparser.getString(); // nameparser.next(); // VALUE_STRINGparser.getString(); // Jason Bourneparser.next(); // KEY_NAMEparser.getString(); // age

Page 38: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 38

JsonParser{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

JsonParser parser = Json.createParser(...);Event e = parser.next(); // START_OBJECT parser.next(); // KEY_NAMEparser.getString(); // nameparser.next(); // VALUE_STRINGparser.getString(); // Jason Bourneparser.next(); // KEY_NAMEparser.getString(); // ageparser.next(); // VALUE_NUMBER

Page 39: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 39

JsonParser{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ]}

JsonParser parser = Json.createParser(...);Event e = parser.next(); // START_OBJECT parser.next(); // KEY_NAMEparser.getString(); // nameparser.next(); // VALUE_STRINGparser.getString(); // Jason Bourneparser.next(); // KEY_NAMEparser.getString(); // ageparser.next(); // VALUE_NUMBERparser.getInt(); // 35

Page 40: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 40

JsonGenerator• Generates JSON in a streaming way to output sources– Similar to StAX’s XMLStreamWriter

• Created using:– Json.createGenerator(…)– Json.createGeneratorFactory().createGenerator(…)

• Optionally, configured with features – e.g. pretty printing

• Allows method chaining

Page 41: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 41

JsonGeneratorJsonGenerator ge=Json.createGenerator(…);ge.writeStartArray() .writeStartObject() .write("type", "home”) .write("number", "123-456-789") .writeEnd() .writeStartObject() .write("type", "fax”) .write("number", "123-456-790") .writeEnd() .writeEnd().close();

[ { "type": "home”, "number": "123-456-789" }, { "type": "fax”, "number": "123-456-790" }]

Page 42: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 42

Object Model API• Builder to build JsonObject and JsonArray from scratch• Allows method chaining• Type-safe (cannot mix array and object building methods)• Can also use existing JsonObject and JsonArray in a builder

Page 43: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 43

Object Model APIJsonArray value = Json.createArrayBuilder() .add(Json.createObjectBuilder() .add("type", "home") .add("number", "123-456-789") ) .add(Json.createObjectBuilder() .add("type", "fax") .add("number", "123-456-790") ) .build();

[ { "type": "home”, "number": "123-456-789" }, { "type": "fax”, "number": "123-456-790" }]

Page 44: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 44

JSON-P 1.1• Update JSON-P spec to stay current with emerging standards (RFC 7159)• Support for IETF standards on – JSON Pointer (RFC 6901)– JSON Patch (RFC 6902)– JSON Merge Patch (RFC 7396)

• Add editing/transformation operations to JSON objects and arrays• Support for a streaming API, together with Collectors• Support for processing big JSON, e.g. add filters to JSON parsing.

Page 45: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 45

JsonPointer• IETF RFC 6901• String syntax for identifying a specific value– /phone/mobile– /parents/0

• Special characters– "/" —> "~1"– "~" —> "~0"

Page 46: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 46

JSON Pointer SampleJsonArray jasons = . . .;JsonPointer pointer = Json.createPointer("/1/profession");JsonValue profession = pointer.getValue(jasons);p.replace(jasons, Json.createValue("Super agent"));

[ { "name": "Jason Voorhees", "profession": "Maniac killer", "age": 45 }, { "name": "Jason Bourne", "profession": "Maniac killer", "age": 35 }]

Page 47: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 47

JsonPatch• IETF RFC 6902• Modify Parts of JSON document• Patch is a JSON document itself• Operations:– Add, replace, remove, move, copy, test

• HTTP PATCH method (application/json-patch+json)

Page 48: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 48

JSON Patch Sample[ { "op": "replace", "path": "/1/profession", "value": "Super agent" }, { "op": "remove", "path": "/2" }]

[ { "name": "Jason Voorhees", "profession": "Maniac killer", "age": 45 }, { "name": "Jason Bourne", "profession": "Maniac killer", "age": 35 }, { "name": "James Bond", "profession": "Agent 007", "age": 40 }]

Page 49: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 49

JSON Patch Sample[ { "op": "replace", "path": "/1/profession", "value": "Super agent" }, { "op": "remove", "path": "/2" }]

[ { "name": "Jason Voorhees", "profession": "Maniac killer", "age": 45 }, { "name": "Jason Bourne", "profession": "Super agent", "age": 35 }, { "name": "James Bond", "profession": "Agent 007", "age": 40 }]

Page 50: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 50

JSON Patch Sample[ { "op": "replace", "path": "/1/profession", "value": "Super agent" }, { "op": "remove", "path": "/2" }]

[ { "name": "Jason Voorhees", "profession": "Maniac killer", "age": 45 }, { "name": "Jason Bourne", "profession": "Super agent", "age": 35 }]

Page 51: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 51

JSON-P Web Sites• Specification – https://json-processing-spec.java.net

• RI: – https://jsonp.java.net

• GitHub – https://github.com/json-p

• JCP– https://jcp.org/en/jsr/detail?id=374

Page 52: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 52

JSON Binding

Page 53: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 53

JSON Binding• API to serialize/deserialize Java objects to/from JSON documents– Similar to JAX-B– Standardizes the current technologies (Jackson, Genson, Gson)

• Default mapping between classes and JSON• Customization APIs– Annotations (@JsonbProperty, @JsonbNillable)– Runtime configuration builder

• Natural follow on to JSON-P– Closes the JSON support gap– Allows to change providers

Page 54: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 54

• No configuration, no annotations• The scope:– Basic Types– Specific JDK Types– Dates– Classes– Collections/Arrays– Enumerations– JSON-P

Default Mappingimport javax.json.bind.Jsonb;import javax.json.bind.JsonbBuilder;

// Create with default configJsonb jsonb = JsonbBuilder.create();

Page 55: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 55

JSON-B Enginepublic interface Jsonb extends AutoCloseable { <T> T fromJson(String str, Class<T> type); <T> T fromJson(String str, Type runtimeType); <T> T fromJson(Reader reader, Class<T> type); <T> T fromJson(Reader reader, Type runtimeType); <T> T fromJson(InputStream stream, Class<T> type); <T> T fromJson(InputStream stream, Type runtimeType);

String toJson(Object object); String toJson(Object object, Type runtimeType); void toJson(Object object, Writer writer); void toJson(Object object, Type runtimeType, Writer writer); void toJson(Object object, OutputStream stream); void toJson(Object object, Type runtimeType, OutputStream stream);}

Page 56: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 56

JSON-B SamplePerson person1 = new Person();person1.setName("Jason Voorhees");person1.setProfession("Maniac killer");person1.setAge(45);

Person person2 = new Person();person2.setName("Jason Bourne");person2.setProfession("Super agent");person2.setAge(35);

List<Person> persons = new ArrayList<>();persons.add(person1);persons.add(person2);

Jsonb jsonb = JsonbBuilder.create();jsonb.toJson(persons);

[ { "name": "Jason Voorhees", "profession": "Maniac killer", "age": 45 }, { "name": "Jason Bourne", "profession": "Super agent", "age": 35 }]

Page 57: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 57

Basic Types– java.lang.String– java.lang.Character– java.lang.Byte (byte)– java.lang.Short (short)– java.lang.Integer (int)– java.lang.Long (long)– java.lang.Float (float)– java.lang.Double (double)– java.lang.Boolean (boolean)

Specific Types– java.math.BigInteger– java.math.BigDecimal– java.net.URL– java.net.URI– java.util.Optional– java.util.OptionalInt– java.util.OptionalLong– java.util.OptionalDouble

Basic and Specific Types

Page 58: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 58

Date/Timejava.util.Date ISO_DATE_TIME

java.util.Calendar, java.util.GregorianCalendar ISO_DATE if to time information present, otherwise ISO_DATE_TIME

Java.util.TimeZone, java.util.SimpleTimeZone NormalizedCustomId (see TimeZone javadoc)

java.time.Instant ISO_INSTANT

java.time.LocalDate ISO_LOCAL_DATE

java.time.LocalTime ISO_LOCAL_TIME

java.time.LocalDateTime ISO_LOCAL_DATE_TIME

java.time.ZonedDateTime ISO_ZONED_DATE_TIME

java.time.OffsetDateTime ISO_OFFSET_DATE_TIME

java.time.OffsetTime ISO_OFFSET_TIME

java.time.ZoneId NormalizedZoneId as specified in ZoneId javadoc

java.time.ZoneOffset NormalizedZoneId as specified in ZoneOffset javadoc

java.time.Duration ISO 8601 seconds based representation

java.time.Period ISO 8601 period representation

Page 59: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 59

Date/Time Samples// java.util.DateSimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");Date parsedDate = sdf.parse("15.11.2016");jsonb.toJson(parsedDate)); // ”2016-11-15T00:00:00"

// java.util.CalendarCalendar dateCalendar = Calendar.getInstance();dateCalendar.clear();dateCalendar.set(2016, 11, 15);jsonb.toJson(dateCalendar); // ”2016-11-15”

// java.time.Instantjsonb.toJson(Instant.parse("2016-11-15T23:00:00Z")); // ”2016-11-15T23:00:00Z”

// java.time.Durationjsonb.toJson(Duration.ofHours(5).plusMinutes(4)); // “PT5H4M"

// java.time.Periodjsonb.toJson(Period.between(

LocalDate.of(1960, Month.JANUARY, 1),LocalDate.of(1970, Month.JANUARY, 1))); // "P10Y"

Page 60: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 60

Arrays/Collections• Collection• Map• Set• HashSet• NavigableSet• SortedSet• TreeSet• LinkedHashSet• TreeHashSet• HashMap

• NavigableMap• SortedMap• TreeMap• LinkedHashMap• TreeHashMap• List• ArrayList• LinkedList• Deque• ArrayDeque

• Queue• PriorityQueue• EnumSet• EnumMap

Page 61: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 61

• javax.json.JsonArray• javax.json.JsonStructure• javax.json.JsonValue• javax.json.JsonPointer• javax.json.JsonString• javax.json.JsonNumber• javax.json.JsonObject

JSON-P Types// JsonObjectJsonBuilderFactory f =

Json.createBuilderFactory(null);

JsonObject jsonObject = f.createObjectBuilder()

.add(“name", "Jason Bourne") .add(“city", "Prague") .build();

jsonb.toJson(jsonObject);

Page 62: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 62

Classes• Public and protected nested and static nested classes• Anonymous classes (serialization only)• Inheritance is supported• Default no-argument constructor is required for deserialization

Page 63: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 63

Fields• Final fields are serialized• Static fields are skipped• Transient fields are skipped• Null fields are skipped• Fields order– Lexicographical order– Parent class fields are serialized before child class fields

Page 64: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 64

public class Parent { public int parentB; public int parentA;}

{ "parentA": 1, "parentB": 2}

Fields Order Sample

Page 65: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 65

public class Parent { public int parentB; public int parentA;}

public class Child extends Parent { public int childB; public int childA;}

{ "parentA": 1, "parentB": 2}

{ "parentA": 1, "parentB": 2,

"childA": 3, "childB": 4}

Fields Order Sample

Page 66: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 66

Serialization• Existing fields with public getters• Public fields with no getters• Public getter/setter pair without a

corresponding field

• Deserialization• Existing fields with public setters• Public fields with no setters• Public getter/setter pair without a

corresponding field

Scope and Field Access Strategy

Page 67: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 67

public class Foo { public final int publicFinalField; private final int privateFinalField;

public static int publicStaticField;

public int publicWithNoGetter; public int publicWithPrivateGetter; public Integer publicNullField = null;

private int privateWithNoGetter; private int privateWithPublicGetter;

public int getNoField() {}; public void setNoField(int value) {};}

{ "publicFinalField": 1,

"publicWithNoGetter": 1,

"privateWithPublicGetter": 1, "noField": 1}

Scope and Field Access Strategy

Page 68: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 68

• Annotations• Runtime configuration– JsonbConfig– JsonbBuilder

JSON-B Engine ConfigurationJsonbConfig config = new JsonbConfig() .withFormatting(…) .withNullValues(…) .withEncoding(…) .withStrictIJSON(…) .withPropertyNamingStrategy(…) .withPropertyOrderStrategy(…) .withPropertyVisibilityStrategy(…) .withAdapters(…) .withBinaryDataStrategy(…);

Jsonb jsonb = JsonbBuilder.newBuilder() .withConfig(…) .withProvider(…) .build();

Page 69: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 69

Customizations• Property names• Property order• Ignoring properties• Null handling• Custom instantiation

• Fields visibility• Date/Number Formats• Binary Encoding• Adapters• Serializers/Deserializers

Page 70: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 70

• Annotation–@JsonbProperty

• Scope:– Field– Getter/Setter– Parameter

Property Namespublic class Customer { private int id;

@JsonbProperty("name") private String firstName;}

public class Customer { public int id; public String firstName;

@JsonbProperty("name") public String getFirstName() { return firstName; }}

Page 71: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 71

Property Naming Strategy• Supported naming strategies– IDENTITY (myMixedCaseProperty)– LOWER_CASE_WITH_DASHES (my-mixed-case-property)– LOWER_CASE_WITH_UNDERSCORES (my_mixed_case_property)– UPPER_CAMEL_CASE (MyMixedCaseProperty)– UPPER_CAMEL_CASE_WITH_SPACES (My Mixed Case Property)– CASE_INSENSITIVE (mYmIxEdCaSePrOpErTy)–Or a custom implementation

• JsonbConfig–withPropertyNamingStrategy(…):

Page 72: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 72

• Strategies:– LEXICOGRAPHICAL (A-Z)– ANY– REVERSE (Z-A)

• Annotation–@JsonbPropertyOrder on class

• JsonbConfig–withPropertyOrderStrategy(…)

Property Order Strategy@JsonbPropertyOrder(ANY)public class Foo { public int bar2; public int bar1;}

Page 73: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 73

• Annotation–@JsonbTransient

Ignoring Propertiespublic class Customer { public int id;

public String name;

@JsonbTransient public BigDecimal salary;}

Page 74: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 74

• PropertyVisibilityStrategyinterface• Annotation–@JsonbVisibility

• JsonbConfig–withPropertyVisibilityStrategy(…)

Property Visibilitypublic interface PropertyVisibilityStrategy { boolean isVisible(Field field); boolean isVisible(Method method);}

public class MuStrategy implements PropertyVisibilityStrategy { /* ... */}

@JsonbVisibility(MyStrategy.class)public class Bar { private int field1; private int field2;}

Page 75: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 75

• Null fields are skipped by default• Annotation–@JsonbNillable

• JsonbConfig–withNullValues(true)

Null Handlingpublic class Customer { public int id = 1;

@JsonbNillable public String name = null;}

@JsonbNillablepublic class Customer { public int id = 1; public String name = null;}

Page 76: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 76

public class Customer { public int id; public String name;

@JsonbCreator public static Customer getFromDb(int id) { return CustomerDao.getByPrimaryKey(id); }}

public class Order { public int id; public Customer customer;}

{ "id": 123, "customer": { "id": 562, }}

Custom Instantiation

Page 77: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 77

• Annotations–@JsonbDateFormat–@JsonbNumberFormat

• JsonbConfig–withDateFormat(…)–withLocale(…)

Date/Number Formatpublic class FormatSample { public Date defaultDate;

@JsonbDateFormat("dd.MM.yyyy") public Date formattedDate;

public BigDecimal defaultNumber;

@JsonbNumberFormat(“#0.00") public BigDecimal formattedNumber; }

Page 78: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 78

• Supported encodings– BYTE (default)– BASE_64– BASE_64_URL

• JsonbConfig–withBinaryDataStrategy(…)

Binary Data EncodingJsonbConfig config = new JsonbConfig() .withBinaryDataStrategy( BinaryDataStrategy.BASE_64);

Jsonb jsonb = JsonbBuilder.create(config);String json = jsonb.toJson(obj);

Page 79: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 79

I-JSON• I-JSON (”Internet JSON”) is a restricted profile of JSON– https://tools.ietf.org/html/draft-ietf-json-i-json-06

• JSON-B fully supports I-JSON by default with three exceptions:– JSON Binding does not restrict the serialization of top-level JSON texts that are

neither objects nor arrays. The restriction should happen at application level.– JSON Binding does not serialize binary data with base64url encoding.– JSON Binding does not enforce additional restrictions on dates/times/duration.

• JsonbConfig–withStrictIJSON(true)

Page 80: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 80

• Inspired by JAXB• Annotations–@JsonbTypeAdapter annotation

• JsonbConfig–withAdapters(…)

Adapterspublic interface JsonbAdapter<Original, Adapted> { Adapted adaptToJson(Original obj); Original adaptFromJson(Adapted obj);}

@JsonbTypeAdapter(AnimalAdapter.class)public Animal animal;

JsonbConfig config = new JsonbConfig() .withAdapters(new AnimalAdapter());

Page 81: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 81

• Low level control onserialization/deserialization• Annotations–@JsonbTypeSerializer–@JsonbTypeDeserializer

• JsonbConfig–withSerializers(…)–withDeserializers(…)

Serializers/Deserializerspublic interface JsonbSerializer<T> { void serialize(T obj, JsonGenerator generator,

SerializationContext ctx);

public interface JsonbDeserializer<T> { T deserialize(JsonParser parser,

DeserializationContext ctx, Type rtType);}

@JsonbTypeSerializer(AnimalSerializer.class)@JsonbTypeDeserializer(AnimalDeserializer.class) public Animal animal;

JsonbConfig config = new JsonbConfig() .withSerializers(new AnimalSerializer()) .withDeserializers(new AnimalDeserializer());

Page 82: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 82

JSON-B Demo• GitHub– https://github.com/m0mus/JavaOne2016-JSONB-Demo

• Demonstrates– Default mapping– Adapters– Serializers–Mapping of generic class

Page 83: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 83

JSON-B Web Sites• JSON-B web site– http://json-b.net

• JSON-B on GitHub– https://github.com/json-b

• JCP.org page– https://www.jcp.org/en/jsr/detail?id=367

• Specification Project: – https://java.net/projects/jsonb-spec

Page 84: JSON Support in Java EE 8

Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 84

Q & A

Page 85: JSON Support in Java EE 8