Más contenido relacionado
La actualidad más candente (20)
Similar a What's new in the Java API for JSON Binding (20)
Más de Dmitry Kornilov (10)
What's new in the Java API for JSON Binding
- 1. 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
dmitry.kornilov@oracle.com
@m0mus
Sep 19, 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. |
Program Agenda
What is JSON-B?
JSR Status & Progress
API Overview
What’s next
Q&A
1
2
3
4
5
3
- 4. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
What is JSON-B?
4
- 5. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
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
5
- 6. 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",
}
- 7. 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",
}
- 8. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
What is JSON Binding?
8
JAX-RS
Objects
XML
JSON
- 9. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
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.
9
- 10. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
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.
10
- 11. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
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.
11
- 12. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Supported Platforms
• Java EE 7
• Java SE 8
• Targeted for inclusion to Java EE 8
• One of the core parts of Java EE Next
12
- 13. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | 13
Java EE 8 Survey (2014)
- 14. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | 14
DZone and Java EE Guardians Java EE 8 Survey
- 15. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
JSR Status & Progress
15
- 16. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
JSR 367 Status
https://www.jcp.org/en/jsr/detail?id=367
16
- 17. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
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
17
- 18. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
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
18
- 19. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
New Awesome Logo
Created by Carla De Bona
@carladebona
19
- 20. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
New Stunning Web Site
• Json-b.net
• Hosted on GitHub
• Created by
Ehsan Zaery Moghaddam
@zaerymoghaddam
20
- 21. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Participate!
users@jsonb-spec.java.net
dmitry.kornilov@oracle.com
21
- 22. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Community Help Needed
• Reference Implementation
– Tests on real life use cases
– Performance testing
– Performance comparison
– Performance optimization
• Evangelism
– Samples, guides, manuals
– Blog articles
22
- 23. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
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
23
- 24. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Summary
24
• 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
- 25. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
API Overview
25
- 26. 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
26
Default Mapping
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
// Create with default config
Jsonb jsonb = JsonbBuilder.create();
- 27. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. | 27
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);
}
- 28. 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
28
Basic and Specific Types
- 29. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Date/Time
29
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
- 30. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Date/Time Samples
30
// java.util.Date
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
Date parsedDate = sdf.parse("25.10.2015");
jsonb.toJson(parsedDate)); // ”2015-10-25T00:00:00"
// java.util.Calendar
Calendar dateCalendar = Calendar.getInstance();
dateCalendar.clear();
dateCalendar.set(2015, 10, 25);
jsonb.toJson(dateCalendar); // ”2015-10-25”
// java.time.Instant
jsonb.toJson(Instant.parse("2015-10-25T23:00:00Z")); // ”2015-10-25T23: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"
- 31. 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
31
- 32. 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
32
JSON-P Types
// JsonObject
JsonBuilderFactory f =
Json.createBuilderFactory(null);
JsonObject jsonObject =
f.createObjectBuilder()
.add(“name", "Jason")
.add(“city", "Prague")
.build();
jsonb.toJson(jsonObject);
- 33. 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
33
- 34. 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
34
- 35. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
public class Parent {
public int parentB;
public int parentA;
}
{
"parentA": 1,
"parentB": 2
}
35
Fields Order Sample
- 36. 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
}
36
Fields Order Sample
- 37. 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
37
Scope and Field Access Strategy
- 38. 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
}
38
Scope and Field Access Strategy
- 39. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Customized Mapping
39
- 40. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
• Annotations
• Runtime configuration
– JsonbConfig
– JsonbBuilder
40
JSON-B Engine Configuration
JsonbConfig config = new JsonbConfig()
.withFormatting(…)
.withNullValues(…)
.withEncoding(…)
.withStrictIJSON(…)
.withPropertyNamingStrategy(…)
.withPropertyOrderStrategy(…)
.withPropertyVisibilityStrategy(…)
.withAdapters(…)
.withBinaryDataStrategy(…);
Jsonb jsonb = JsonbBuilder.newBuilder()
.withConfig(…)
.withProvider(…)
.build();
- 41. 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
- 42. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
• Annotation
– @JsonbProperty
• Scope:
– Field
– Getter/Setter
– Parameter
42
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;
}
}
- 43. 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(…):
43
- 44. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
• Strategies:
– LEXICOGRAPHICAL (A-Z)
– ANY
– REVERSE (Z-A)
• Annotation
– @JsonbPropertyOrder on class
• JsonbConfig
– withPropertyOrderStrategy(…)
44
Property Order Strategy
@JsonbPropertyOrder(ANY)
public class Foo {
public int bar2;
public int bar1;
}
- 45. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
• Annotation
– @JsonbTransient
45
Ignoring Properties
public class Customer {
public int id;
public String name;
@JsonbTransient
public BigDecimal salary;
}
- 46. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
• PropertyVisibilityStrategy
interface
• Annotation
– @JsonbVisibility
• JsonbConfig
– withPropertyVisibilityStrategy(…)
46
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;
}
- 47. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
• Null fields are skipped by default
• Annotation
– @JsonbNillable
• JsonbConfig
– withNullValues(true)
47
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;
}
- 48. 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,
}
}
48
Custom Instantiation
- 49. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
• Annotations
– @JsonbDateFormat
– @JsonbNumberFormat
• JsonbConfig
– withDateFormat(…)
– withLocale(…)
49
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;
}
- 50. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
• Supported encodings
– BYTE (default)
– BASE_64
– BASE_64_URL
• JsonbConfig
– withBinaryDataStrategy(…)
50
Binary Data Encoding
JsonbConfig config = new JsonbConfig()
.withBinaryDataStrategy(
BinaryDataStrategy.BASE_64);
Jsonb jsonb = JsonbBuilder.create(config);
String json = jsonb.toJson(obj);
- 51. 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)
51
- 52. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
• Inspired by JAXB
• Annotations
– @JsonbTypeAdapter annotation
• JsonbConfig
– withAdapters(…)
52
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());
- 53. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
• Low level control on
serialization/deserialization
• Annotations
– @JsonbTypeSerializer
– @JsonbTypeDeserializer
• JsonbConfig
– withSerializers(…)
– withDeserializers(…)
53
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());
- 54. 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
• Hackergarten
– Hilton San Francisco Union Square - Java Hub at the Java Exhibition Hall
Tuesday, 20 Sep 2016, 15:00-17:00
54
- 55. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
What’s Next
55
- 56. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
JSON-B 1.1
• Integration with other Java EE frameworks (JAX-RS, JPA)
• JSON Pointer
• Partial Mapping
56
- 57. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
How to meet?
• JCP Meeting Room
Hilton San Francisco Union Square
Tuesdsay, 20 Sep 2016, 12:00-13:30
• Hackergarten
Hilton San Francisco Union Square - Java Hub at the Java Exhibition Hall
Tuesday, 20 Sep 2016, 15:00-17:00
57
- 58. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
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
58
- 59. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Next Steps
• Take the survey
– http://glassfish.org/survey
• Send technical comments to
– users@javaee-spec.java.net
• 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
59
- 60. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
Where to Learn More at JavaOne
60
Session 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.