62
Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | What's new in the Java API for JSON Binding Dmitry Kornilov JSON-B spec lead [email protected] @m0mus Sep 19, 2016

What's new in the Java API for JSON Binding

Embed Size (px)

Citation preview

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

What's new in the Java API for JSON Binding

Dmitry KornilovJSON-B spec lead

[email protected]@m0mus

Sep 19, 2016

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.

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

Program Agenda

What is JSON-B?

JSR Status & Progress

API Overview

What’s next

Q&A

1

2

3

4

5

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

What is JSON-B?

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

What is JSON Binding?• JSON Binding is a JSR• JSON Binding = JSON-B = JSONB = JSR 367• It’s about converting Java objects to and from JSON documents

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

What is JSON Binding?

Java JSON

public class Customer { public int id; public String firstName; public String lastName; ….}

Customer c = new Customer();c.id = 1;c.firstName = "John";c.lastName = "Doe”;

{ "id": 1, "firstName" : "John", "lastName" : "Doe",}

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

What is JSON Binding?

Java JSON

JSON-Bpublic class Customer { public int id; public String firstName; public String lastName; ….}

Customer c = new Customer();c.id = 1;c.firstName = "John";c.lastName = "Doe”;

{ "id": 1, "firstName" : "John", "lastName" : "Doe",}

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

What is JSON Binding?

JAX-RS

Objects

XML

JSON

JAXB

JSON-B

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

Goals• JSON– Support of all RFC 7159-compatible JSON documents.

• JSON specifications– JSON-related specifications has to be surveyed to determine their relationship to

JSON-Binding.

• Consistency–Maintain consistency with JAXB and other Java EE and SE APIs where appropriate.

• Convention– Define default mapping of Java classes and instances to JSON document counterparts.

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

Goals (continue)• Customization– Allow customization of the default mapping definition.

• Easy of use– Default use of the APIs should not require prior knowledge of the JSON document

format and specification.

• Integration– Define or enable integration with JSR 374: Java API for JSON Processing (JSON-P) 1.1.

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

Non-Goals• Preserving equivalence (Round-trip) – The specification recommends, but does not require equivalence of content for

deserialized and serialized JSON documents.

• JSON Schema – Generation of JSON Schema from Java classes, as well as validation based on JSON

schema.

• JEP 198 Lightweight JSON API – Support and integration with Lightweight JSON API as defined within JEP 198 is out of

scope of this specification.

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

Supported Platforms• Java EE 7• Java SE 8• Targeted for inclusion to Java EE 8• One of the core parts of Java EE Next

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

Java EE 8 Survey (2014)

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

DZone and Java EE Guardians Java EE 8 Survey

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

JSR Status & Progress

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

JSR 367 Statushttps://www.jcp.org/en/jsr/detail?id=367

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

What’s done last year• The specification– Public Review was published (25 May 2016)– Public Review ballot is passed (26 July 2016)

• Reference Implementation– All functionality is implemented– Snapshot is published

• TCK development is started

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

What’s new in the API• New Adapters – Inspired by JAXB

• Serializers and Deserializers– Low level access to JSON-P generator/parser

• @JsonbValue removed– This functionality is covered by adapters

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

New Awesome LogoCreated by Carla De Bona@carladebona

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

New Stunning Web Site• Json-b.net• Hosted on GitHub• Created by

Ehsan Zaery Moghaddam@zaerymoghaddam

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

[email protected]

[email protected]

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

Community Help Needed• Reference Implementation– Tests on real life use cases – Performance testing – Performance comparison – Performance optimization

• Evangelism– Samples, guides, manuals– Blog articles

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

Adopt a JSR• We are participating in Adopt-a-JSR program– Presentation for CZ JUG– Presentation for Bentonville JUG– Faso JUG Adopts JSR 367• https://github.com/pandaconstantin/adopjsrfasojug

• Contact me if you need a presentation for your JUG

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

Summary• 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

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

API Overview

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

• 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();

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

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);}

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

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

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

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

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

Date/Time Samples// java.util.DateSimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");Date parsedDate = sdf.parse("25.10.2015");jsonb.toJson(parsedDate)); // ”2015-10-25T00:00:00"

// java.util.CalendarCalendar dateCalendar = Calendar.getInstance();dateCalendar.clear();dateCalendar.set(2015, 10, 25);jsonb.toJson(dateCalendar); // ”2015-10-25”

// java.time.Instantjsonb.toJson(Instant.parse("2015-10-25T23:00:00Z")); // ”2015-10-25T23: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"

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

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

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

• 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") .add(“city", "Prague") .build();

jsonb.toJson(jsonObject);

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

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

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

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

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

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

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

Fields Order Sample

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

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

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

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

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

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

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

Customized Mapping

39

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

• 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();

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

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

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

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

• 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; }}

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

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(…):

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

• 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;}

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

• Annotation–@JsonbTransient

Ignoring Propertiespublic class Customer { public int id;

public String name;

@JsonbTransient public BigDecimal salary;}

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

• 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;}

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

• 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;}

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

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

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

• 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; }

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

• 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);

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

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)

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

• 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());

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

• 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());

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

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

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

• Hackergarten– Hilton San Francisco Union Square - Java Hub at the Java Exhibition Hall

Tuesday, 20 Sep 2016, 15:00-17:00

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

What’s Next

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

JSON-B 1.1• Integration with other Java EE frameworks (JAX-RS, JPA)• JSON Pointer• Partial Mapping

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

How to meet?• JCP Meeting Room

Hilton San Francisco Union SquareTuesdsay, 20 Sep 2016, 12:00-13:30• Hackergarten

Hilton San Francisco Union Square - Java Hub at the Java Exhibition HallTuesday, 20 Sep 2016, 15:00-17:00

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

Special Thanks• Roman Grigoriadi for great work on RI• Carla De Bona for awesome logo• Ehsan Zaery Moghaddam for the stunning web site• Reza Rahman for support• All Experts and Users for participation

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

Next Steps

• Take the survey– http://glassfish.org/survey

• Send technical comments to– [email protected]

• Join the JCP – come to Hackergarden in Java Hub– https://jcp.org/en/participation/membership_drive

• Join or track the JSRs as they progress– https://java.net/projects/javaee-spec/pages/Specifications

• Adopt-a-JSR– https://community.oracle.com/community/java/jcp/adopt-a-jsr

Give us your feedback

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

Where to Learn More at JavaOneSession Number Session Title Day / Time

BOF7984 Java EE for the Cloud Monday 7:00 p.m.CON4022 CDI 2.0 Is Coming Tuesday 11:00 a.m.CON7983 JAX-RS 2.1 for Java EE 8 Tuesday 12:30 p.m.CON8292 Portable Cloud Applications with Java EE Tuesday 2:30 p.m.CON7980 Servlet 4.0: Status Update and HTTP/2 Tuesday 4:00 p.m.CON7978 Security for Java EE 8 and the Cloud Tuesday 5:30 p.m.CON7979 Configuration for Java EE 8 and the Cloud Wednesday 11:30 a.m.

CON7977 Java EE Next – HTTP/2 and REST Wednesday 1:00 p.m.CON6077 The Illusion of Statelessness Wednesday 4:30 p.m.CON 7981 JSF 2.3 Thursday 11:30 a.m.

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

Q & A