SlideShare uma empresa Scribd logo
1 de 85
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
JSON support in Java EE 8
Dmitry Kornilov
JSONB/P Specification Lead
@m0mus
Werner Keil
JSON-P EG Member
@wernerkeil
November 15, 2016
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
Safe Harbor Statement
The 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.
2
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
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
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
Program Agenda
Introduction
JSON Processing
JSON Binding
Q & A
1
2
3
5
5
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
Introduction
6
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 7
What is JSON???
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
This is Jason
8
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
This is also Jason
9
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
This is JSON-B
10
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
What is JSON?
• JavaScript Object Notation
• Subset of JavaScript
• Lightweight data-interchange format
• Object, Array, Value
11
{
"name": "Jason Bourne",
"age": 35,
"phoneNumbers": [
{
"type": "home",
"number": "123-456-789"
}
]
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
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
12
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
JSON Processing
13
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
JSON-P
• Streaming API
– JsonParser
– JsonGenerator
• Object model API
– JsonReader
– JsonWriter
– JsonPointer
– JsonPatch
– JsonMergePatch
14
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
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
15
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 16
JsonParser
{
"name":
"Jason Bourne",
"age":
35,
"phoneNumbers":
[
{
"type": "home",
"number": "123-456-789"
}
]
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 17
JsonParser
START_OBJECT{
"name":
"Jason Bourne",
"age":
35,
"phoneNumbers":
[
{
"type": "home",
"number": "123-456-789"
}
]
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 18
JsonParser
START_OBJECT
KEY_NAME
{
"name":
"Jason Bourne",
"age":
35,
"phoneNumbers":
[
{
"type": "home",
"number": "123-456-789"
}
]
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 19
JsonParser
START_OBJECT
KEY_NAME
VALUE_STRING
{
"name":
"Jason Bourne",
"age":
35,
"phoneNumbers":
[
{
"type": "home",
"number": "123-456-789"
}
]
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 20
JsonParser
START_OBJECT
KEY_NAME
VALUE_STRING
KEY_NAME
{
"name":
"Jason Bourne",
"age":
35,
"phoneNumbers":
[
{
"type": "home",
"number": "123-456-789"
}
]
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 21
JsonParser
START_OBJECT
KEY_NAME
VALUE_STRING
KEY_NAME
VALUE_NUMBER
{
"name":
"Jason Bourne",
"age":
35,
"phoneNumbers":
[
{
"type": "home",
"number": "123-456-789"
}
]
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 22
JsonParser
START_OBJECT
KEY_NAME
VALUE_STRING
KEY_NAME
VALUE_NUMBER
KEY_NAME
{
"name":
"Jason Bourne",
"age":
35,
"phoneNumbers":
[
{
"type": "home",
"number": "123-456-789"
}
]
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 23
JsonParser
START_OBJECT
KEY_NAME
VALUE_STRING
KEY_NAME
VALUE_NUMBER
KEY_NAME
START_ARRAY
{
"name":
"Jason Bourne",
"age":
35,
"phoneNumbers":
[
{
"type": "home",
"number": "123-456-789"
}
]
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 24
JsonParser
START_OBJECT
KEY_NAME
VALUE_STRING
KEY_NAME
VALUE_NUMBER
KEY_NAME
START_ARRAY
START_OBJECT
{
"name":
"Jason Bourne",
"age":
35,
"phoneNumbers":
[
{
"type": "home",
"number": "123-456-789"
}
]
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 25
JsonParser
START_OBJECT
KEY_NAME
VALUE_STRING
KEY_NAME
VALUE_NUMBER
KEY_NAME
START_ARRAY
START_OBJECT
KEY_NAME, KEY_STRING
{
"name":
"Jason Bourne",
"age":
35,
"phoneNumbers":
[
{
"type": "home",
"number": "123-456-789"
}
]
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 26
JsonParser
START_OBJECT
KEY_NAME
VALUE_STRING
KEY_NAME
VALUE_NUMBER
KEY_NAME
START_ARRAY
START_OBJECT
KEY_NAME, KEY_STRING
KEY_NAME, KEY_STRING
{
"name":
"Jason Bourne",
"age":
35,
"phoneNumbers":
[
{
"type": "home",
"number": "123-456-789"
}
]
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 27
JsonParser
START_OBJECT
KEY_NAME
VALUE_STRING
KEY_NAME
VALUE_NUMBER
KEY_NAME
START_ARRAY
START_OBJECT
KEY_NAME, KEY_STRING
KEY_NAME, KEY_STRING
END_OBJECT
{
"name":
"Jason Bourne",
"age":
35,
"phoneNumbers":
[
{
"type": "home",
"number": "123-456-789"
}
]
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 28
JsonParser
START_OBJECT
KEY_NAME
VALUE_STRING
KEY_NAME
VALUE_NUMBER
KEY_NAME
START_ARRAY
START_OBJECT
KEY_NAME, KEY_STRING
KEY_NAME, KEY_STRING
END_OBJECT
END_ARRAY
{
"name":
"Jason Bourne",
"age":
35,
"phoneNumbers":
[
{
"type": "home",
"number": "123-456-789"
}
]
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 29
JsonParser
START_OBJECT
KEY_NAME
VALUE_STRING
KEY_NAME
VALUE_NUMBER
KEY_NAME
START_ARRAY
START_OBJECT
KEY_NAME, KEY_STRING
KEY_NAME, KEY_STRING
END_OBJECT
END_ARRAY
END_OBJECT
{
"name":
"Jason Bourne",
"age":
35,
"phoneNumbers":
[
{
"type": "home",
"number": "123-456-789"
}
]
}
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(...);
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
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
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_NAME
parser.getString(); // name
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_NAME
parser.getString(); // name
parser.next(); // VALUE_STRING
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_NAME
parser.getString(); // name
parser.next(); // VALUE_STRING
parser.getString(); // Jason Bourne
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_NAME
parser.getString(); // name
parser.next(); // VALUE_STRING
parser.getString(); // Jason Bourne
parser.next(); // KEY_NAME
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_NAME
parser.getString(); // name
parser.next(); // VALUE_STRING
parser.getString(); // Jason Bourne
parser.next(); // KEY_NAME
parser.getString(); // age
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_NAME
parser.getString(); // name
parser.next(); // VALUE_STRING
parser.getString(); // Jason Bourne
parser.next(); // KEY_NAME
parser.getString(); // age
parser.next(); // VALUE_NUMBER
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_NAME
parser.getString(); // name
parser.next(); // VALUE_STRING
parser.getString(); // Jason Bourne
parser.next(); // KEY_NAME
parser.getString(); // age
parser.next(); // VALUE_NUMBER
parser.getInt(); // 35
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
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
40
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 41
JsonGenerator
JsonGenerator 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"
}
]
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
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
42
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 43
Object Model API
JsonArray 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"
}
]
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
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.
44
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
JsonPointer
• IETF RFC 6901
• String syntax for identifying a specific value
– /phone/mobile
– /parents/0
• Special characters
– "/" —> "~1"
– "~" —> "~0"
45
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
JSON Pointer Sample
JsonArray jasons = . . .;
JsonPointer pointer =
Json.createPointer("/1/profession");
JsonValue profession =
pointer.getValue(jasons);
p.replace(jasons,
Json.createValue("Super agent"));
46
[
{
"name": "Jason Voorhees",
"profession": "Maniac killer",
"age": 45
},
{
"name": "Jason Bourne",
"profession": "Maniac killer",
"age": 35
}
]
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
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)
47
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
}
]
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
}
]
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
}
]
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
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
51
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
JSON Binding
52
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
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
53
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
• No configuration, no annotations
• The scope:
– Basic Types
– Specific JDK Types
– Dates
– Classes
– Collections/Arrays
– Enumerations
– JSON-P
54
Default Mapping
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
// Create with default config
Jsonb jsonb = JsonbBuilder.create();
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 55
JSON-B Engine
public 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);
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
JSON-B Sample
56
Person 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
}
]
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
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
57
Basic and Specific Types
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
Date/Time
58
java.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
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
Date/Time Samples
59
// java.util.Date
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
Date parsedDate = sdf.parse("15.11.2016");
jsonb.toJson(parsedDate)); // ”2016-11-15T00:00:00"
// java.util.Calendar
Calendar dateCalendar = Calendar.getInstance();
dateCalendar.clear();
dateCalendar.set(2016, 11, 15);
jsonb.toJson(dateCalendar); // ”2016-11-15”
// java.time.Instant
jsonb.toJson(Instant.parse("2016-11-15T23:00:00Z")); // ”2016-11-15T23:00:00Z”
// java.time.Duration
jsonb.toJson(Duration.ofHours(5).plusMinutes(4)); // “PT5H4M"
// java.time.Period
jsonb.toJson(Period.between(
LocalDate.of(1960, Month.JANUARY, 1),
LocalDate.of(1970, Month.JANUARY, 1))); // "P10Y"
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
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
60
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
• javax.json.JsonArray
• javax.json.JsonStructure
• javax.json.JsonValue
• javax.json.JsonPointer
• javax.json.JsonString
• javax.json.JsonNumber
• javax.json.JsonObject
61
JSON-P Types
// JsonObject
JsonBuilderFactory f =
Json.createBuilderFactory(null);
JsonObject jsonObject =
f.createObjectBuilder()
.add(“name", "Jason Bourne")
.add(“city", "Prague")
.build();
jsonb.toJson(jsonObject);
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
Classes
• Public and protected nested and static nested classes
• Anonymous classes (serialization only)
• Inheritance is supported
• Default no-argument constructor is required for deserialization
62
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
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
63
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
public class Parent {
public int parentB;
public int parentA;
}
{
"parentA": 1,
"parentB": 2
}
64
Fields Order Sample
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
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
}
65
Fields Order Sample
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
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
66
Scope and Field Access Strategy
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
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
}
67
Scope and Field Access Strategy
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
• Annotations
• Runtime configuration
– JsonbConfig
– JsonbBuilder
68
JSON-B Engine Configuration
JsonbConfig config = new JsonbConfig()
.withFormatting(…)
.withNullValues(…)
.withEncoding(…)
.withStrictIJSON(…)
.withPropertyNamingStrategy(…)
.withPropertyOrderStrategy(…)
.withPropertyVisibilityStrategy(…)
.withAdapters(…)
.withBinaryDataStrategy(…);
Jsonb jsonb = JsonbBuilder.newBuilder()
.withConfig(…)
.withProvider(…)
.build();
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
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
• Annotation
– @JsonbProperty
• Scope:
– Field
– Getter/Setter
– Parameter
70
Property Names
public 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;
}
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
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(…):
71
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
• Strategies:
– LEXICOGRAPHICAL (A-Z)
– ANY
– REVERSE (Z-A)
• Annotation
– @JsonbPropertyOrder on class
• JsonbConfig
– withPropertyOrderStrategy(…)
72
Property Order Strategy
@JsonbPropertyOrder(ANY)
public class Foo {
public int bar2;
public int bar1;
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
• Annotation
– @JsonbTransient
73
Ignoring Properties
public class Customer {
public int id;
public String name;
@JsonbTransient
public BigDecimal salary;
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
• PropertyVisibilityStrategy
interface
• Annotation
– @JsonbVisibility
• JsonbConfig
– withPropertyVisibilityStrategy(…)
74
Property Visibility
public 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;
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
• Null fields are skipped by default
• Annotation
– @JsonbNillable
• JsonbConfig
– withNullValues(true)
75
Null Handling
public class Customer {
public int id = 1;
@JsonbNillable
public String name = null;
}
@JsonbNillable
public class Customer {
public int id = 1;
public String name = null;
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
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,
}
}
76
Custom Instantiation
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
• Annotations
– @JsonbDateFormat
– @JsonbNumberFormat
• JsonbConfig
– withDateFormat(…)
– withLocale(…)
77
Date/Number Format
public class FormatSample {
public Date defaultDate;
@JsonbDateFormat("dd.MM.yyyy")
public Date formattedDate;
public BigDecimal defaultNumber;
@JsonbNumberFormat(“#0.00")
public BigDecimal formattedNumber;
}
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
• Supported encodings
– BYTE (default)
– BASE_64
– BASE_64_URL
• JsonbConfig
– withBinaryDataStrategy(…)
78
Binary Data Encoding
JsonbConfig config = new JsonbConfig()
.withBinaryDataStrategy(
BinaryDataStrategy.BASE_64);
Jsonb jsonb = JsonbBuilder.create(config);
String json = jsonb.toJson(obj);
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
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)
79
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
• Inspired by JAXB
• Annotations
– @JsonbTypeAdapter annotation
• JsonbConfig
– withAdapters(…)
80
Adapters
public 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());
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
• Low level control on
serialization/deserialization
• Annotations
– @JsonbTypeSerializer
– @JsonbTypeDeserializer
• JsonbConfig
– withSerializers(…)
– withDeserializers(…)
81
Serializers/Deserializers
public 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());
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
JSON-B Demo
• GitHub
– https://github.com/m0mus/JavaOne2016-JSONB-Demo
• Demonstrates
– Default mapping
– Adapters
– Serializers
– Mapping of generic class
82
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
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
83
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
Q & A
84
JSON Support in Java EE 8

Mais conteúdo relacionado

Mais procurados

Querying Linked Data with SPARQL
Querying Linked Data with SPARQLQuerying Linked Data with SPARQL
Querying Linked Data with SPARQLOlaf Hartig
 
APEX Office Hours Interactive Grid Deep Dive
APEX Office Hours Interactive Grid Deep DiveAPEX Office Hours Interactive Grid Deep Dive
APEX Office Hours Interactive Grid Deep DiveJohnSnyders
 
RDF Tutorial - SPARQL 20091031
RDF Tutorial - SPARQL 20091031RDF Tutorial - SPARQL 20091031
RDF Tutorial - SPARQL 20091031kwangsub kim
 
Open Standards for the Semantic Web: XML / RDF(S) / OWL / SOAP
Open Standards for the Semantic Web: XML / RDF(S) / OWL / SOAPOpen Standards for the Semantic Web: XML / RDF(S) / OWL / SOAP
Open Standards for the Semantic Web: XML / RDF(S) / OWL / SOAPPieter De Leenheer
 
20180420 hk-the powerofmysql8
20180420 hk-the powerofmysql820180420 hk-the powerofmysql8
20180420 hk-the powerofmysql8Ivan Ma
 
20190615 hkos-mysql-troubleshootingandperformancev2
20190615 hkos-mysql-troubleshootingandperformancev220190615 hkos-mysql-troubleshootingandperformancev2
20190615 hkos-mysql-troubleshootingandperformancev2Ivan Ma
 
Linking the world with Python and Semantics
Linking the world with Python and SemanticsLinking the world with Python and Semantics
Linking the world with Python and SemanticsTatiana Al-Chueyr
 
Tutorial "An Introduction to SPARQL and Queries over Linked Data" Chapter 1 (...
Tutorial "An Introduction to SPARQL and Queries over Linked Data" Chapter 1 (...Tutorial "An Introduction to SPARQL and Queries over Linked Data" Chapter 1 (...
Tutorial "An Introduction to SPARQL and Queries over Linked Data" Chapter 1 (...Olaf Hartig
 
Using Edition-Based Redefinition for Zero Downtime PL/SQL Changes
Using Edition-Based Redefinition for Zero Downtime PL/SQL ChangesUsing Edition-Based Redefinition for Zero Downtime PL/SQL Changes
Using Edition-Based Redefinition for Zero Downtime PL/SQL ChangesChris Saxon
 
Making Java REST with JAX-RS 2.0
Making Java REST with JAX-RS 2.0Making Java REST with JAX-RS 2.0
Making Java REST with JAX-RS 2.0Dmytro Chyzhykov
 
20190817 coscup-oracle my sql innodb cluster sharing
20190817 coscup-oracle my sql innodb cluster sharing20190817 coscup-oracle my sql innodb cluster sharing
20190817 coscup-oracle my sql innodb cluster sharingIvan Ma
 
So various polymorphism in Scala
So various polymorphism in ScalaSo various polymorphism in Scala
So various polymorphism in Scalab0ris_1
 
Jfokus 2017 Oracle Dev Cloud and Containers
Jfokus 2017 Oracle Dev Cloud and ContainersJfokus 2017 Oracle Dev Cloud and Containers
Jfokus 2017 Oracle Dev Cloud and ContainersMika Rinne
 
The Semantics of SPARQL
The Semantics of SPARQLThe Semantics of SPARQL
The Semantics of SPARQLOlaf Hartig
 
Neo4j Introduction (Basics, Cypher, RDBMS to GRAPH)
Neo4j Introduction (Basics, Cypher, RDBMS to GRAPH) Neo4j Introduction (Basics, Cypher, RDBMS to GRAPH)
Neo4j Introduction (Basics, Cypher, RDBMS to GRAPH) David Fombella Pombal
 

Mais procurados (20)

Querying Linked Data with SPARQL
Querying Linked Data with SPARQLQuerying Linked Data with SPARQL
Querying Linked Data with SPARQL
 
RDFa Tutorial
RDFa TutorialRDFa Tutorial
RDFa Tutorial
 
APEX Office Hours Interactive Grid Deep Dive
APEX Office Hours Interactive Grid Deep DiveAPEX Office Hours Interactive Grid Deep Dive
APEX Office Hours Interactive Grid Deep Dive
 
RDF Tutorial - SPARQL 20091031
RDF Tutorial - SPARQL 20091031RDF Tutorial - SPARQL 20091031
RDF Tutorial - SPARQL 20091031
 
4 sw architectures and sparql
4 sw architectures and sparql4 sw architectures and sparql
4 sw architectures and sparql
 
Java EE Next
Java EE NextJava EE Next
Java EE Next
 
Open Standards for the Semantic Web: XML / RDF(S) / OWL / SOAP
Open Standards for the Semantic Web: XML / RDF(S) / OWL / SOAPOpen Standards for the Semantic Web: XML / RDF(S) / OWL / SOAP
Open Standards for the Semantic Web: XML / RDF(S) / OWL / SOAP
 
20180420 hk-the powerofmysql8
20180420 hk-the powerofmysql820180420 hk-the powerofmysql8
20180420 hk-the powerofmysql8
 
20190615 hkos-mysql-troubleshootingandperformancev2
20190615 hkos-mysql-troubleshootingandperformancev220190615 hkos-mysql-troubleshootingandperformancev2
20190615 hkos-mysql-troubleshootingandperformancev2
 
Linking the world with Python and Semantics
Linking the world with Python and SemanticsLinking the world with Python and Semantics
Linking the world with Python and Semantics
 
Tutorial "An Introduction to SPARQL and Queries over Linked Data" Chapter 1 (...
Tutorial "An Introduction to SPARQL and Queries over Linked Data" Chapter 1 (...Tutorial "An Introduction to SPARQL and Queries over Linked Data" Chapter 1 (...
Tutorial "An Introduction to SPARQL and Queries over Linked Data" Chapter 1 (...
 
JAX-RS 2.1 Reloaded
JAX-RS 2.1 ReloadedJAX-RS 2.1 Reloaded
JAX-RS 2.1 Reloaded
 
Using Edition-Based Redefinition for Zero Downtime PL/SQL Changes
Using Edition-Based Redefinition for Zero Downtime PL/SQL ChangesUsing Edition-Based Redefinition for Zero Downtime PL/SQL Changes
Using Edition-Based Redefinition for Zero Downtime PL/SQL Changes
 
Making Java REST with JAX-RS 2.0
Making Java REST with JAX-RS 2.0Making Java REST with JAX-RS 2.0
Making Java REST with JAX-RS 2.0
 
JavaCro'15 - Java Certification – in theory and practice - Branko Mihaljević,...
JavaCro'15 - Java Certification – in theory and practice - Branko Mihaljević,...JavaCro'15 - Java Certification – in theory and practice - Branko Mihaljević,...
JavaCro'15 - Java Certification – in theory and practice - Branko Mihaljević,...
 
20190817 coscup-oracle my sql innodb cluster sharing
20190817 coscup-oracle my sql innodb cluster sharing20190817 coscup-oracle my sql innodb cluster sharing
20190817 coscup-oracle my sql innodb cluster sharing
 
So various polymorphism in Scala
So various polymorphism in ScalaSo various polymorphism in Scala
So various polymorphism in Scala
 
Jfokus 2017 Oracle Dev Cloud and Containers
Jfokus 2017 Oracle Dev Cloud and ContainersJfokus 2017 Oracle Dev Cloud and Containers
Jfokus 2017 Oracle Dev Cloud and Containers
 
The Semantics of SPARQL
The Semantics of SPARQLThe Semantics of SPARQL
The Semantics of SPARQL
 
Neo4j Introduction (Basics, Cypher, RDBMS to GRAPH)
Neo4j Introduction (Basics, Cypher, RDBMS to GRAPH) Neo4j Introduction (Basics, Cypher, RDBMS to GRAPH)
Neo4j Introduction (Basics, Cypher, RDBMS to GRAPH)
 

Semelhante a JSON Support in Java EE 8

JSON Support in Java EE 8
JSON Support in Java EE 8JSON Support in Java EE 8
JSON Support in Java EE 8Dmitry Kornilov
 
Java API for JSON Binding - Introduction and update
Java API for JSON Binding - Introduction and updateJava API for JSON Binding - Introduction and update
Java API for JSON Binding - Introduction and updateMartin Grebac
 
Java EE 8 - An instant snapshot
Java EE 8 - An instant snapshotJava EE 8 - An instant snapshot
Java EE 8 - An instant snapshotDavid Delabassee
 
JSON and the Oracle Database
JSON and the Oracle DatabaseJSON and the Oracle Database
JSON and the Oracle DatabaseMaria Colgan
 
Making Sense of Schema on Read
Making Sense of Schema on ReadMaking Sense of Schema on Read
Making Sense of Schema on ReadKent Graziano
 
Configuration for Java EE: Config JSR and Tamaya
Configuration for Java EE: Config JSR and TamayaConfiguration for Java EE: Config JSR and Tamaya
Configuration for Java EE: Config JSR and TamayaDmitry Kornilov
 
Java Script Based Client Server Webapps 2
Java Script Based Client Server Webapps 2Java Script Based Client Server Webapps 2
Java Script Based Client Server Webapps 2kriszyp
 
Elasticsearch in 15 minutes
Elasticsearch in 15 minutesElasticsearch in 15 minutes
Elasticsearch in 15 minutesDavid Pilato
 
Do More with Postgres- NoSQL Applications for the Enterprise
Do More with Postgres- NoSQL Applications for the EnterpriseDo More with Postgres- NoSQL Applications for the Enterprise
Do More with Postgres- NoSQL Applications for the EnterpriseEDB
 
LF_APIStrat17_Embracing JSON Schema
LF_APIStrat17_Embracing JSON SchemaLF_APIStrat17_Embracing JSON Schema
LF_APIStrat17_Embracing JSON SchemaLF_APIStrat
 
Java EE 8 - An instant snapshot
Java EE 8 - An instant snapshot Java EE 8 - An instant snapshot
Java EE 8 - An instant snapshot David Delabassee
 

Semelhante a JSON Support in Java EE 8 (20)

JSON Support in Java EE 8
JSON Support in Java EE 8JSON Support in Java EE 8
JSON Support in Java EE 8
 
Introduction to Yasson
Introduction to YassonIntroduction to Yasson
Introduction to Yasson
 
Java API for JSON Binding - Introduction and update
Java API for JSON Binding - Introduction and updateJava API for JSON Binding - Introduction and update
Java API for JSON Binding - Introduction and update
 
Java EE 7 overview
Java EE 7 overviewJava EE 7 overview
Java EE 7 overview
 
Java EE 8 - An instant snapshot
Java EE 8 - An instant snapshotJava EE 8 - An instant snapshot
Java EE 8 - An instant snapshot
 
JSON and the Oracle Database
JSON and the Oracle DatabaseJSON and the Oracle Database
JSON and the Oracle Database
 
Making Sense of Schema on Read
Making Sense of Schema on ReadMaking Sense of Schema on Read
Making Sense of Schema on Read
 
Json tutorial, a beguiner guide
Json tutorial, a beguiner guideJson tutorial, a beguiner guide
Json tutorial, a beguiner guide
 
Configuration for Java EE: Config JSR and Tamaya
Configuration for Java EE: Config JSR and TamayaConfiguration for Java EE: Config JSR and Tamaya
Configuration for Java EE: Config JSR and Tamaya
 
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
 
Hands on JSON
Hands on JSONHands on JSON
Hands on JSON
 
Json
JsonJson
Json
 
Advanced Json
Advanced JsonAdvanced Json
Advanced Json
 
Java Script Based Client Server Webapps 2
Java Script Based Client Server Webapps 2Java Script Based Client Server Webapps 2
Java Script Based Client Server Webapps 2
 
Elasticsearch in 15 minutes
Elasticsearch in 15 minutesElasticsearch in 15 minutes
Elasticsearch in 15 minutes
 
Do More with Postgres- NoSQL Applications for the Enterprise
Do More with Postgres- NoSQL Applications for the EnterpriseDo More with Postgres- NoSQL Applications for the Enterprise
Do More with Postgres- NoSQL Applications for the Enterprise
 
Json
JsonJson
Json
 
LF_APIStrat17_Embracing JSON Schema
LF_APIStrat17_Embracing JSON SchemaLF_APIStrat17_Embracing JSON Schema
LF_APIStrat17_Embracing JSON Schema
 
Java EE 8 - An instant snapshot
Java EE 8 - An instant snapshot Java EE 8 - An instant snapshot
Java EE 8 - An instant snapshot
 
JavaCro'15 - Java EE 8 - An instant snapshot - David Delabassee
JavaCro'15 - Java EE 8 - An instant snapshot - David DelabasseeJavaCro'15 - Java EE 8 - An instant snapshot - David Delabassee
JavaCro'15 - Java EE 8 - An instant snapshot - David Delabassee
 

Mais de Dmitry Kornilov

Helidon Nima - Loom based microserfice framework.pptx
Helidon Nima - Loom based microserfice framework.pptxHelidon Nima - Loom based microserfice framework.pptx
Helidon Nima - Loom based microserfice framework.pptxDmitry Kornilov
 
Jakarta EE: Today and Tomorrow
Jakarta EE: Today and TomorrowJakarta EE: Today and Tomorrow
Jakarta EE: Today and TomorrowDmitry Kornilov
 
Building Cloud-Native Applications with Helidon
Building Cloud-Native Applications with HelidonBuilding Cloud-Native Applications with Helidon
Building Cloud-Native Applications with HelidonDmitry Kornilov
 
Nonblocking Database Access in Helidon SE
Nonblocking Database Access in Helidon SENonblocking Database Access in Helidon SE
Nonblocking Database Access in Helidon SEDmitry Kornilov
 
JSON Support in Jakarta EE: Present and Future
JSON Support in Jakarta EE: Present and FutureJSON Support in Jakarta EE: Present and Future
JSON Support in Jakarta EE: Present and FutureDmitry Kornilov
 
Building cloud native microservices with project Helidon
Building cloud native microservices with project HelidonBuilding cloud native microservices with project Helidon
Building cloud native microservices with project HelidonDmitry Kornilov
 
Developing cloud-native microservices using project Helidon
Developing cloud-native microservices using project HelidonDeveloping cloud-native microservices using project Helidon
Developing cloud-native microservices using project HelidonDmitry Kornilov
 
From Java EE to Jakarta EE
From Java EE to Jakarta EEFrom Java EE to Jakarta EE
From Java EE to Jakarta EEDmitry Kornilov
 
Helidon: Java Libraries for Writing Microservices
Helidon: Java Libraries for Writing MicroservicesHelidon: Java Libraries for Writing Microservices
Helidon: Java Libraries for Writing MicroservicesDmitry Kornilov
 
Adopt-a-JSR session (JSON-B/P)
Adopt-a-JSR session (JSON-B/P)Adopt-a-JSR session (JSON-B/P)
Adopt-a-JSR session (JSON-B/P)Dmitry Kornilov
 

Mais de Dmitry Kornilov (11)

Helidon Nima - Loom based microserfice framework.pptx
Helidon Nima - Loom based microserfice framework.pptxHelidon Nima - Loom based microserfice framework.pptx
Helidon Nima - Loom based microserfice framework.pptx
 
Jakarta EE: Today and Tomorrow
Jakarta EE: Today and TomorrowJakarta EE: Today and Tomorrow
Jakarta EE: Today and Tomorrow
 
Building Cloud-Native Applications with Helidon
Building Cloud-Native Applications with HelidonBuilding Cloud-Native Applications with Helidon
Building Cloud-Native Applications with Helidon
 
Nonblocking Database Access in Helidon SE
Nonblocking Database Access in Helidon SENonblocking Database Access in Helidon SE
Nonblocking Database Access in Helidon SE
 
JSON Support in Jakarta EE: Present and Future
JSON Support in Jakarta EE: Present and FutureJSON Support in Jakarta EE: Present and Future
JSON Support in Jakarta EE: Present and Future
 
Building cloud native microservices with project Helidon
Building cloud native microservices with project HelidonBuilding cloud native microservices with project Helidon
Building cloud native microservices with project Helidon
 
Developing cloud-native microservices using project Helidon
Developing cloud-native microservices using project HelidonDeveloping cloud-native microservices using project Helidon
Developing cloud-native microservices using project Helidon
 
From Java EE to Jakarta EE
From Java EE to Jakarta EEFrom Java EE to Jakarta EE
From Java EE to Jakarta EE
 
Helidon: Java Libraries for Writing Microservices
Helidon: Java Libraries for Writing MicroservicesHelidon: Java Libraries for Writing Microservices
Helidon: Java Libraries for Writing Microservices
 
Adopt-a-JSR session (JSON-B/P)
Adopt-a-JSR session (JSON-B/P)Adopt-a-JSR session (JSON-B/P)
Adopt-a-JSR session (JSON-B/P)
 
Java EE for the Cloud
Java EE for the CloudJava EE for the Cloud
Java EE for the Cloud
 

Último

Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxDyna Gilbert
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predieusebiomeyer
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITMgdsc13
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一Fs
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa494f574xmv
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)Christopher H Felton
 
Elevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New OrleansElevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New Orleanscorenetworkseo
 
Intellectual property rightsand its types.pptx
Intellectual property rightsand its types.pptxIntellectual property rightsand its types.pptx
Intellectual property rightsand its types.pptxBipin Adhikari
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一z xss
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一Fs
 
Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMartaLoveguard
 
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书rnrncn29
 
Q4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptxQ4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptxeditsforyah
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Excelmac1
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一Fs
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书zdzoqco
 

Último (20)

Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptx
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predi
 
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITM
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
 
Elevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New OrleansElevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New Orleans
 
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
 
Intellectual property rightsand its types.pptx
Intellectual property rightsand its types.pptxIntellectual property rightsand its types.pptx
Intellectual property rightsand its types.pptx
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
 
Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptx
 
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
 
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
 
Q4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptxQ4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptx
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
 

JSON Support in Java EE 8

  • 1. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. JSON support in Java EE 8 Dmitry Kornilov JSONB/P Specification Lead @m0mus Werner Keil JSON-P EG Member @wernerkeil November 15, 2016
  • 2. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. Safe Harbor Statement The 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. 2
  • 3. 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
  • 4. 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
  • 5. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. Program Agenda Introduction JSON Processing JSON Binding Q & A 1 2 3 5 5
  • 6. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. Introduction 6
  • 7. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 7 What is JSON???
  • 8. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. This is Jason 8
  • 9. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. This is also Jason 9
  • 10. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. This is JSON-B 10
  • 11. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. What is JSON? • JavaScript Object Notation • Subset of JavaScript • Lightweight data-interchange format • Object, Array, Value 11 { "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ] }
  • 12. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 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 12
  • 13. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. JSON Processing 13
  • 14. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. JSON-P • Streaming API – JsonParser – JsonGenerator • Object model API – JsonReader – JsonWriter – JsonPointer – JsonPatch – JsonMergePatch 14
  • 15. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 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 15
  • 16. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 16 JsonParser { "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ] }
  • 17. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 17 JsonParser START_OBJECT{ "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ] }
  • 18. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 18 JsonParser START_OBJECT KEY_NAME { "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ] }
  • 19. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 19 JsonParser START_OBJECT KEY_NAME VALUE_STRING { "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ] }
  • 20. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 20 JsonParser START_OBJECT KEY_NAME VALUE_STRING KEY_NAME { "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ] }
  • 21. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 21 JsonParser START_OBJECT KEY_NAME VALUE_STRING KEY_NAME VALUE_NUMBER { "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ] }
  • 22. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 22 JsonParser START_OBJECT KEY_NAME VALUE_STRING KEY_NAME VALUE_NUMBER KEY_NAME { "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ] }
  • 23. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 23 JsonParser START_OBJECT KEY_NAME VALUE_STRING KEY_NAME VALUE_NUMBER KEY_NAME START_ARRAY { "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ] }
  • 24. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 24 JsonParser START_OBJECT KEY_NAME VALUE_STRING KEY_NAME VALUE_NUMBER KEY_NAME START_ARRAY START_OBJECT { "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ] }
  • 25. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 25 JsonParser START_OBJECT KEY_NAME VALUE_STRING KEY_NAME VALUE_NUMBER KEY_NAME START_ARRAY START_OBJECT KEY_NAME, KEY_STRING { "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ] }
  • 26. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 26 JsonParser START_OBJECT KEY_NAME VALUE_STRING KEY_NAME VALUE_NUMBER KEY_NAME START_ARRAY START_OBJECT KEY_NAME, KEY_STRING KEY_NAME, KEY_STRING { "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ] }
  • 27. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 27 JsonParser START_OBJECT KEY_NAME VALUE_STRING KEY_NAME VALUE_NUMBER KEY_NAME START_ARRAY START_OBJECT KEY_NAME, KEY_STRING KEY_NAME, KEY_STRING END_OBJECT { "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ] }
  • 28. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 28 JsonParser START_OBJECT KEY_NAME VALUE_STRING KEY_NAME VALUE_NUMBER KEY_NAME START_ARRAY START_OBJECT KEY_NAME, KEY_STRING KEY_NAME, KEY_STRING END_OBJECT END_ARRAY { "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ] }
  • 29. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 29 JsonParser START_OBJECT KEY_NAME VALUE_STRING KEY_NAME VALUE_NUMBER KEY_NAME START_ARRAY START_OBJECT KEY_NAME, KEY_STRING KEY_NAME, KEY_STRING END_OBJECT END_ARRAY END_OBJECT { "name": "Jason Bourne", "age": 35, "phoneNumbers": [ { "type": "home", "number": "123-456-789" } ] }
  • 30. 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(...);
  • 31. 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
  • 32. 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
  • 33. 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_NAME parser.getString(); // name
  • 34. 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_NAME parser.getString(); // name parser.next(); // VALUE_STRING
  • 35. 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_NAME parser.getString(); // name parser.next(); // VALUE_STRING parser.getString(); // Jason Bourne
  • 36. 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_NAME parser.getString(); // name parser.next(); // VALUE_STRING parser.getString(); // Jason Bourne parser.next(); // KEY_NAME
  • 37. 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_NAME parser.getString(); // name parser.next(); // VALUE_STRING parser.getString(); // Jason Bourne parser.next(); // KEY_NAME parser.getString(); // age
  • 38. 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_NAME parser.getString(); // name parser.next(); // VALUE_STRING parser.getString(); // Jason Bourne parser.next(); // KEY_NAME parser.getString(); // age parser.next(); // VALUE_NUMBER
  • 39. 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_NAME parser.getString(); // name parser.next(); // VALUE_STRING parser.getString(); // Jason Bourne parser.next(); // KEY_NAME parser.getString(); // age parser.next(); // VALUE_NUMBER parser.getInt(); // 35
  • 40. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 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 40
  • 41. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 41 JsonGenerator JsonGenerator 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" } ]
  • 42. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 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 42
  • 43. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 43 Object Model API JsonArray 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" } ]
  • 44. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 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. 44
  • 45. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. JsonPointer • IETF RFC 6901 • String syntax for identifying a specific value – /phone/mobile – /parents/0 • Special characters – "/" —> "~1" – "~" —> "~0" 45
  • 46. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. JSON Pointer Sample JsonArray jasons = . . .; JsonPointer pointer = Json.createPointer("/1/profession"); JsonValue profession = pointer.getValue(jasons); p.replace(jasons, Json.createValue("Super agent")); 46 [ { "name": "Jason Voorhees", "profession": "Maniac killer", "age": 45 }, { "name": "Jason Bourne", "profession": "Maniac killer", "age": 35 } ]
  • 47. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 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) 47
  • 48. 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 } ]
  • 49. 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 } ]
  • 50. 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 } ]
  • 51. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 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 51
  • 52. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. JSON Binding 52
  • 53. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 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 53
  • 54. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. • No configuration, no annotations • The scope: – Basic Types – Specific JDK Types – Dates – Classes – Collections/Arrays – Enumerations – JSON-P 54 Default Mapping import javax.json.bind.Jsonb; import javax.json.bind.JsonbBuilder; // Create with default config Jsonb jsonb = JsonbBuilder.create();
  • 55. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 55 JSON-B Engine public 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); }
  • 56. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. JSON-B Sample 56 Person 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 } ]
  • 57. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 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 57 Basic and Specific Types
  • 58. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. Date/Time 58 java.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
  • 59. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. Date/Time Samples 59 // java.util.Date SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy"); Date parsedDate = sdf.parse("15.11.2016"); jsonb.toJson(parsedDate)); // ”2016-11-15T00:00:00" // java.util.Calendar Calendar dateCalendar = Calendar.getInstance(); dateCalendar.clear(); dateCalendar.set(2016, 11, 15); jsonb.toJson(dateCalendar); // ”2016-11-15” // java.time.Instant jsonb.toJson(Instant.parse("2016-11-15T23:00:00Z")); // ”2016-11-15T23:00:00Z” // java.time.Duration jsonb.toJson(Duration.ofHours(5).plusMinutes(4)); // “PT5H4M" // java.time.Period jsonb.toJson(Period.between( LocalDate.of(1960, Month.JANUARY, 1), LocalDate.of(1970, Month.JANUARY, 1))); // "P10Y"
  • 60. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 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 60
  • 61. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. • javax.json.JsonArray • javax.json.JsonStructure • javax.json.JsonValue • javax.json.JsonPointer • javax.json.JsonString • javax.json.JsonNumber • javax.json.JsonObject 61 JSON-P Types // JsonObject JsonBuilderFactory f = Json.createBuilderFactory(null); JsonObject jsonObject = f.createObjectBuilder() .add(“name", "Jason Bourne") .add(“city", "Prague") .build(); jsonb.toJson(jsonObject);
  • 62. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. Classes • Public and protected nested and static nested classes • Anonymous classes (serialization only) • Inheritance is supported • Default no-argument constructor is required for deserialization 62
  • 63. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 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 63
  • 64. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. public class Parent { public int parentB; public int parentA; } { "parentA": 1, "parentB": 2 } 64 Fields Order Sample
  • 65. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 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 } 65 Fields Order Sample
  • 66. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 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 66 Scope and Field Access Strategy
  • 67. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 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 } 67 Scope and Field Access Strategy
  • 68. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. • Annotations • Runtime configuration – JsonbConfig – JsonbBuilder 68 JSON-B Engine Configuration JsonbConfig config = new JsonbConfig() .withFormatting(…) .withNullValues(…) .withEncoding(…) .withStrictIJSON(…) .withPropertyNamingStrategy(…) .withPropertyOrderStrategy(…) .withPropertyVisibilityStrategy(…) .withAdapters(…) .withBinaryDataStrategy(…); Jsonb jsonb = JsonbBuilder.newBuilder() .withConfig(…) .withProvider(…) .build();
  • 69. 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
  • 70. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. • Annotation – @JsonbProperty • Scope: – Field – Getter/Setter – Parameter 70 Property Names public 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; } }
  • 71. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 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(…): 71
  • 72. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. • Strategies: – LEXICOGRAPHICAL (A-Z) – ANY – REVERSE (Z-A) • Annotation – @JsonbPropertyOrder on class • JsonbConfig – withPropertyOrderStrategy(…) 72 Property Order Strategy @JsonbPropertyOrder(ANY) public class Foo { public int bar2; public int bar1; }
  • 73. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. • Annotation – @JsonbTransient 73 Ignoring Properties public class Customer { public int id; public String name; @JsonbTransient public BigDecimal salary; }
  • 74. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. • PropertyVisibilityStrategy interface • Annotation – @JsonbVisibility • JsonbConfig – withPropertyVisibilityStrategy(…) 74 Property Visibility public 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; }
  • 75. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. • Null fields are skipped by default • Annotation – @JsonbNillable • JsonbConfig – withNullValues(true) 75 Null Handling public class Customer { public int id = 1; @JsonbNillable public String name = null; } @JsonbNillable public class Customer { public int id = 1; public String name = null; }
  • 76. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 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, } } 76 Custom Instantiation
  • 77. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. • Annotations – @JsonbDateFormat – @JsonbNumberFormat • JsonbConfig – withDateFormat(…) – withLocale(…) 77 Date/Number Format public class FormatSample { public Date defaultDate; @JsonbDateFormat("dd.MM.yyyy") public Date formattedDate; public BigDecimal defaultNumber; @JsonbNumberFormat(“#0.00") public BigDecimal formattedNumber; }
  • 78. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. • Supported encodings – BYTE (default) – BASE_64 – BASE_64_URL • JsonbConfig – withBinaryDataStrategy(…) 78 Binary Data Encoding JsonbConfig config = new JsonbConfig() .withBinaryDataStrategy( BinaryDataStrategy.BASE_64); Jsonb jsonb = JsonbBuilder.create(config); String json = jsonb.toJson(obj);
  • 79. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 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) 79
  • 80. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. • Inspired by JAXB • Annotations – @JsonbTypeAdapter annotation • JsonbConfig – withAdapters(…) 80 Adapters public 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());
  • 81. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. • Low level control on serialization/deserialization • Annotations – @JsonbTypeSerializer – @JsonbTypeDeserializer • JsonbConfig – withSerializers(…) – withDeserializers(…) 81 Serializers/Deserializers public 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());
  • 82. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. JSON-B Demo • GitHub – https://github.com/m0mus/JavaOne2016-JSONB-Demo • Demonstrates – Default mapping – Adapters – Serializers – Mapping of generic class 82
  • 83. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 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 83
  • 84. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. Q & A 84