SlideShare ist ein Scribd-Unternehmen logo
1 von 79
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.
JSONB introduction
and comparison with other frameworks
Dmitry Kornilov
JSON-B spec lead
@m0mus
Roman Grigoriadi
JSON-B RI lead engineer
@bravehorsie
Copyright © 2015, 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 © 2015, Oracle and/or its affiliates. All rights reserved. 3
Program Agenda
1. What is JSON-B
2. JSR-367 status
3. Default mapping
4. Customized mapping
5. Demo application
6. JSON-B RI
7. Q&A
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 4
• JSON Binding is a standard
• It’s about converting Java objects to and from JSON documents
• JSON Binding = JSON-B = JSONB = JSR 367
What is JSON Binding?
4
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 5
What is JSON Binding?
5
public class Customer {
public int id;
public String firstName;
public String lastName;
….
}
Customer e = new Customer();
e.id = 1;
e.firstName = “John”;
e.lastName = “Doe”;
{
"id": 1,
"firstName" : "John",
"lastName" : "Doe",
}
Java JSON
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 6
What is JSON Binding?
6
public class Customer {
public int id;
public String firstName;
public String lastName;
….
}
Customer e = new Customer();
e.id = 1;
e.firstName = “John”;
e.lastName = “Doe”;
{
"id": 1,
"firstName" : "John",
"lastName" : "Doe",
}
Java JSON
JSON-B
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 7
• Genson
• Gson
• Jackson
• …
Alternatives
7
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
JSON-B Standard
8
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 99
Java Community Process
• JSR-367
• JSR status and updates
• Expert group
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 1010
Specification and API Project
• Hosted on java.net
• Spec in pdf format
• Git repository
• Wiki
• Bug tracker
• Mailing lists
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 1111
Participate!
users@jsonb-spec.java.net
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 1212
Reference Implementation
• eclipselink.org/jsonb
• Mirror on GitHub
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 1313
Summary
• JCP Page
https://www.jcp.org/en/jsr/detail?id=367
• Specification Project Home:
https://java.net/projects/jsonb-spec
• API sources & samples:
https://java.net/projects/jsonb-spec/sources/git/show/api
• Specification in pdf:
https://java.net/projects/jsonb-spec/sources/git/content/spec/spec.pdf
• Reference implementation:
http://eclipselink.org/jsonb
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
JSON-B Default Mapping
14
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 1515
Default Mapping
• No configuration, no annotations
• The scope:
– Basic Types
– Specific JDK Types
– Dates
– Classes
– Collections/Arrays
– Enumerations
– JSON-P
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
// Create with default config
Jsonb jsonb = JsonbBuilder.create();
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.
• toJson(…)
• fromJson(…)
1616
JSON-B Engine
String toJson(Object object);
String toJson(Object object, Type runtimeType);
void toJson(Object object, Writer writer);
void toJson(Object object, Type runtimeType, Writer appendable);
void toJson(Object object, OutputStream stream);
void toJson(Object object, Type runtimeType, OutputStream stream);
<T> T fromJson(String str, Class<T> type);
<T> T fromJson(String str, Type runtimeType);
<T> T fromJson(Reader readable, Class<T> type);
<T> T fromJson(Reader readable, Type runtimeType);
<T> T fromJson(InputStream stream, Class<T> type);
<T> T fromJson(InputStream stream, Type runtimeType);
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 1717
Default Mapping – 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)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 1818
Default Mapping – 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)
Serialization:
toString()
Deserialization:
parseXXX()
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 1919
• 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)
Default Mapping – Basic Types
“string”
’u0041’
(byte) 1
(short) 1
(int) 1
1L
1.2f
1.2
true
“string”
“A”
1
1
1
1
1.2
1.2
true
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 2020
Default Mapping – 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
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.
• java.math.BigInteger
• java.math.BigDecimal
• java.net.URL
• java.net.URI
• java.util.Optional
• java.util.OptionalInt
• java.util.OptionalLong
• java.util.OptionalDouble
2121
Default Mapping – Specific Types
Serialization:
toString()
Deserialization:
Single argument constructor
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 2222
Default Mapping – 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
Serialization:
toString()
Deserialization:
Single argument constructor
• Represented by its value if not empty
• Considered null if empty
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 2323
Optional Types
OptionalInt.of(1)
OptionalInt.empty()
JSON-B 1
Genson {"asInt": 1, "present": true}
Gson {”value": 1, "present": true}
Jackson 1
JSON-B null
Genson -
Gson {”value": 0, "present": false}
Jackson null
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 2424
Default Mapping – Dates
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 © 2015, Oracle and/or its affiliates. All rights reserved. 2525
SimpleDateFormat sdf =
new SimpleDateFormat("dd.MM.yyyy");
Date date = sdf.parse("08.03.2016");
Default Mapping – Date Sample
JSON-B “2016-03-08T00:00:00”
Genson 1457391600000
Gson "Mar 8, 2016 12:00:00 AM”
Jackson 1457391600000
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 2626
Default Mapping – Calendar Sample
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(2016, 3, 8);
JSON-B “2016-03-08”
Genson 1457391600000
Gson {"year":2016,
"month":3,
"dayOfMonth":8,
"hourOfDay":0,
"minute":0,
"second": 0}
Jackson 1457391600000
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 2727
Default Mapping – 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 © 2015, Oracle and/or its affiliates. All rights reserved. 2828
Default Mapping – Fields
• Final fields are serialized
• Static fields are skipped
• Transient fields are skipped
• Null fields are skipped
• Lexicographical order
• Parent class fields are serialized before child class fields
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 2929
Fields Order Comparison
class Parent {
public int parentB = 2;
public int parentA = 1;
}
class Child extends Parent {
public int childB = 4;
public int childA = 3;
}
JSON-B {"parentA":1,"parentB":2,
"childA":3, "childB":4}
Genson {"childA":3, "childB":4,
"parentA":1,"parentB":2}
Gson {"childB":4, "childA":3,
"parentB":2,"parentA":1}
Jackson {"parentB":2,"parentA":1,
"childB":4, "childA":3}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 3030
Default Mapping – Scope and Field Access Strategy
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
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 3131
Scope and Field Access Strategy – JSON-B
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
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 3232
Scope and Field Access Strategy – Genson
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,
"publicWithPrivateGetter": 1,
"publicNullField": null,
"privateWithPublicGetter": 1,
"noField": 1
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 3333
Scope and Field Access Strategy – Gson
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,
"privateFinalField": 1,
"publicWithNoGetter": 1,
"publicWithPrivateGetter": 1,
"privateWithNoGetter": 1,
"privateWithPublicGetter": 1,
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 3434
Scope and Field Access Strategy – Jackson
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,
"publicWithPrivateGetter": 1,
"publicNullField": null,
"privateWithPublicGetter": 1,
"noField": 1
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 3535
Scope and Field Access Strategy – Summary
Framework
Respects
getters/setters
Respects
getter/setter
visibility
Not public fields Virtual fields
JSON-B Yes Yes No Yes
Genson Yes No No Yes
Gson No No Yes No
Jackson Yes No No Yes
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 3636
// Array
int[] intArray = {1, 2, 3};
jsonb.toJson(intArray); // [1,2,3]
// Collection
Collection<Object> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(null);
jsonb.toJson(list); // [1,2,null]
// Map
Map<String, Object> map = new LinkedHashMap<>();
map.put("first", 1);
map.put("second", 2);
jsonb.toJson(map); // {"first":1,"second":2}
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 © 2015, Oracle and/or its affiliates. All rights reserved. 3737
JSON-P Types
• javax.json.JsonArray
• javax.json.JsonStructure
• javax.json.JsonValue
• javax.json.JsonPointer
• javax.json.JsonString
• javax.json.JsonNumber
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 3838
JSON-P Types
• javax.json.JsonArray
• javax.json.JsonStructure
• javax.json.JsonValue
• javax.json.JsonPointer
• javax.json.JsonString
• javax.json.JsonNumber
Serialization:
javax.json.JsonWriter
Deserialization:
javax.json.JsonReader
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 3939
JsonBuilderFactory f =
Json.createBuilderFactory(null);
JsonObject jsonObject = f.createObjectBuilder()
.add(“name", "Jason")
.add(“city", "Prague")
.build();
JSON-P Sample
{
"name": "Jason",
”city": ”Prague"
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 4040
JSON-P Types Support in Other Frameworks
• Genson:
– Support added in JSR353Bundle
• Gson
– No JSON-P support
• Jackson
– Support added in JSR353Module
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Customized Mapping
41
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 4242
JSON-B Engine Configuration
JsonbConfig config = new JsonbConfig()
.withFormatting(…)
.withNullValues(…)
.withEncoding(…)
.withStrictIJSON(…)
.withPropertyNamingStrategy(…)
.withPropertyOrderStrategy(…)
.withPropertyVisibilityStrategy(…)
.withAdapters(…)
.withBinaryDataStrategy(…);
Jsonb jsonb = JsonbBuilder.newBuilder()
.withConfig(…)
.withProvider(…)
.build();
• Annotations
• Runtime configuration
– JsonbConfig
– JsonbBuilder
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 4343
Customizations
• Property names
• Property order
• Ignoring properties
• Null handling
• Custom instantiation
• Fields visibility
• Adapters
• Date/Number Formats
• Binary Encoding
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 4444
Property Name Customization
• JSON-B:
– @JsonbProperty (Field, Method)
• Genson:
– @JsonProperty (Field, Method)
– Use GensonBuilder().rename() method
• Gson:
– @SerializedName (Field)
• Jackson:
– @JsonProperty (Field, Method)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 4545
Custom Mapping - Property Names
public class Customer {
public int id;
public String firstName;
}
{
"id": 1,
"firstName": "Jason"
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 4646
Custom Mapping - 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;
}
}
{
"id": 1,
"name": "Jason"
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 4747
Custom Mapping - Property Names
public class Customer {
public int id;
public String firstName;
@JsonbProperty(“getter-name")
String getFirstName() {
return firstName;
}
@JsonbProperty(“setter-name")
void setFirstName(String str) {
this.firstName = str;
}
}
Serialization:
{
"id": 1,
“getter-name": "Jason"
}
Deserialization:
{
"id": 1,
“setter-name": "Jason"
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 4848
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 © 2015, Oracle and/or its affiliates. All rights reserved.
• Genson
– GensonBuilder.with(PropertyNameResolver… resolvers)
• Gson:
– GsonBuilder.setFieldNamingPolicy(FieldNamingPolicy policy)
• Jackson
– ObjectMapper.setPropertyNamingStrategy(PropertyNamingStrategy pns)
4949
Property Naming Strategy
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 5050
Property Order Strategy
• Strategies:
– LEXICOGRAPHICAL (A-Z)
– ANY
– REVERSE (Z-A)
• Compile Time:
– @JsonbPropertyOrder on class
• Runtime:
– withPropertyOrderStrategy(…)
@JsonbPropertyOrder(ANY)
public class Foo {
public int bar2;
public int bar1;
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.
• Compile Time:
– Transient modifier
– @JsonbTransient annotation
– PropertyVisibilityStrategy interface
– @JsonbVisibility annotation
• Runtime:
– withPropertyVisibilityStrategy(…)
5151
Ignoring Properties and Visibility Customization
public class Foo {
public transient int skipped;
@JsonbTransient
public int alsoSkipped;
}
@JsonbVisibility(MyStrategy.class)
public class Bar {
private int field1;
private int field2;
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.
• Genson
– @JsonIgnore annotation
– Include(…) and exclude(…) methods in GensonBuilder class
• Gson:
– @Exposed annotation
– ExclusionStrategy interface
• Jackson
– @JsonIgnore annotation on field
– @JsonIgnoreProperties annotation on class
– Filters and mix-ins
5252
Ignoring Properties in Other Frameworks
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.
• Null fields are skipped by default
• Compile Time:
– @JsonbNillable annotation
• Runtime:
– JsonbConfig().withNullValues(true)
5353
Null Handling
public class Customer {
public int id = 1;
@JsonbNillable
public String name = null;
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 5454
Null Handling in Other Frameworks
Framework
Serializes
nulls by
default
Null Handling
JSON-B No @JsonbNillable
Genson Yes GensonBuilder.setSkipNull(true)
Gson No GsonBuilder.serializeNulls()
Jackson Yes @JsonInclude(JsonInclude.Include.NON_NULL)
ObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 5555
Custom Instantiation
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": 1,
"customer": {
"id": 2 }
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.
• JAXB inspired JsonbAdapter interface
• @JsonbTypeAdapter annotation
• JsonbConfig().withAdapters(JsonbAdapter… adapters);
5656
Adapters
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.
• Genson
– Converter interface
– JAXB adapters support with JAXBBundle
• Gson:
– TypeAdapter interface
• Jackson
– External serializers
– Mix-In annotations
5757
Adapters in Other Frameworks
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 5858
Date/Number Format
public class FormatTest {
public Date defaultDate;
@JsonbDateFormat("dd.MM.yyyy")
public Date formattedDate;
public BigDecimal defaultNumber;
@JsonbNumberFormat(“#0.00")
public BigDecimal formattedNumber;
}
{
“defaultDate”: “2015-07-26T23:00:00",
“formattedDate”: ”26.07.2015",
“defaultNumber": 1.2,
“formattedNumber": 1.20
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Date/Number Formats in other Frameworks
• Genson
– @JsonDateFormat annotation
– GensonBuilder.setDateFormat(dateFormat)
• Gson:
– GsonBuilder.setDateFormat
• Jackson
– @JsonFormat annotation
– objectMapper.setDateFormat(myDateFormat);
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 6060
Binary Data Encoding
• BYTE (default)
• BASE_64
• BASE_64_URL
JsonbConfig config = new JsonbConfig()
.withBinaryDataStrategy(BinaryDataStrategy.BASE_64);
Jsonb jsonb = JsonbBuilder.create(config);
String json = jsonb.toJson(obj);
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 6161
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.
• Configuration: withStrictIJSONSerializationCompliance
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
JSON-B RI
62
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
JSON-B Demo Application
• https://github.com/bravehorsie/jsonb-demo.git
• Client server web application
• Subject is JSON object, constructed and managed in JavaScript
• Demonstrates:
–Default and customized mappings
–@JsonbProperty annotation
–Adapters
–Virtual properties handling
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 6464
JSON-B Demo Model
public class Hero {
@JsonbProperty("hero_name")
private String name;
@JsonbProperty("hero_class")
private HeroClass heroClass;
@JsonbTypeAdapter(ItemsAdapter.class)
@JsonbProperty("hero_items")
private Map<ItemSlot, Item> items = new HashMap<>();
@JsonbProperty("total_strength")
public Long getTotalStrength() {
return getTotalStat("strength");
}
@JsonbProperty("total_vitality")
public Long getTotalVitality() {
return getTotalStat("vitality");
}
…
}
public class ItemSlot {
private final Long id;
// Head, Shoulders, Chest, Boots, etc.
private final String name;
}
public class Item {
// Tyrael's might, Butcher's Carver
private String name;
private List<Stat> stats;
...
}
public class Stat {
// Strength, Vitality
private String name;
private Integer value;
...
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 6565
JSON-B Demo Servlet
@Override
protected void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException, IOException {
// Unmarshall json to Request object with Hero inside.
Request request = jsonb.fromJson(httpRequest.getInputStream(), Request.class);
Hero hero = request.getHero();
// Generate combat log and loot.
CombatLog combatLog = combatEngine.generateCombatLog(hero);
combatEngine.generateLoot(hero);
// Marshall our hero back to JSON object.
jsonb.toJson(new Response(hero, combatLog), Response.class, httpResponse.getOutputStream());
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
JSON-B Scope and Concurrency
• Thread safe
• Optimal when instance is
created per “class model”
or per configuration.
public class MyRestWsDao {
private final Jsonb jsonb;
public MyRestWsDao() {
JsonbBuilder.create(config);
}
public Response callBusiness(Request req) {
String reqPayload = jsonb.toJson(req);
String respPayload = transport.send(reqPayload);
return jsonb.fromJson(
respPayload, Response.class);
}
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Type Resolution and Generics
• There is no type info in JSON document.
• Type resolution by field / method type declaration
{ ”fileld1": ”value1", “field2": ”value2” }
jsonb.fromJson(json, Pojo.class);
public class Pojo {
private Box box;
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Type Resolution and Generics
• Generic types are resolved by field bounds
// Example 1
private List<Box> boxList;
// Example 2
public class Pojo<X> {
private GenericPojo<Integer> integerGenericPojo;
}
public class GenericPojo<X> {
private List<X> x;
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Type Resolution and Generics
• Generic types for root type must be passed to JSONB
• Deserialization into interfaces is not supported
(besides known types as Map, List, Set, etc..)
public class GenericBox<X> {
private List<X> xList;
private X x;
}
jsonb.fromJson(json, new GenericBox<BigDecimal>() {}.getClass());
public class IncompatibleClass {
public Serializable something;
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
JSON-B Adapters
• JSON-B runtime conversion of one type to another (in addition to pre-
process conversion)
• Customizing types, which you can’t modify (don’t own sources)
• Conversion is needed for just a part of domain model
• Inspired by JAXB XmlAdapter
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 7171
JSON-B Adapter Sample
public class User {
private Long id;
private String email;
private String userName;
private String firstName;
private String surName;
}
{
“email”: ”f.pokorny@centrum.cz",
“firstName": “Frantisek",
“id”: 123,
“userName": “frantaUser",
“surName”: ”Pokorny"
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 7272
JSON-B Adapter Sample
public class AdaptedUser {
@JsonbProperty("USER_ID")
private Long id;
}
{
“USER_ID”: 123
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 7373
JSON-B Adapter Sample
public class UserAdapter implements JsonbAdapter<User, AdaptedUser> {
@Inject
private UserService userService;
@Override
public AdaptedUser adaptToJson(User obj) throws Exception {
return new AdaptedUser(obj.getId());
}
@Override
public User adaptFromJson(AdaptedUser obj) throws Exception {
User user = userService.findById(obj.getId());
return user;
}
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 7474
JSON-B Adapter Sample
public class Hero {
...
@JsonbTypeAdapter(ItemsAdapter.class)
private Map<ItemSlot, Item> items = new HashMap<>();
...
}
public class ItemSlot {
private final Long id;
private final String name;
...
}
public class Item {
private String name;
private List<Stat> stats;
...
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 7575
JSON-B Adapter Sample
public class ItemsAdapter implements JsonbAdapter<Map<ItemSlot, Item>, Map<String, Item>> {
@Override
public Map<String, Item> adaptToJson(Map<ItemSlot, Item> obj) throws Exception {
final Map<String, Item> result = new HashMap<>();
for (Map.Entry<ItemSlot, Item> entry : obj.entrySet()) {
result.put(entry.getKey().getName(), entry.getValue());
}
return result;
}
@Override
public Map<ItemSlot, Item> adaptFromJson(Map<String, Item> obj) throws Exception {
final Map<ItemSlot, Item> result = new HashMap<>();
for (Map.Entry<String, Item> entry : obj.entrySet()) {
ItemSlotEnum slotEnum = ItemSlotEnum.valueOf(entry.getKey());
result.put(new ItemSlot(slotEnum.getId(), slotEnum.name()), entry.getValue());
}
return result;
}
}
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
What’s Next
• Serializers / Deserializers with access to low level JSON-P API
• Polymorphism (@JsonbPolymorphic / PolymorphicAdapter)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 7777
Participate!
users@jsonb-spec.java.net
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Q&A
78
JSON-B for CZJUG

Weitere ähnliche Inhalte

Was ist angesagt?

JSONB introduction and comparison with other frameworks
JSONB introduction and comparison with other frameworksJSONB introduction and comparison with other frameworks
JSONB introduction and comparison with other frameworksDmitry Kornilov
 
Configuration with Apache Tamaya
Configuration with Apache TamayaConfiguration with Apache Tamaya
Configuration with Apache TamayaAnatole Tresch
 
What's coming in Java EE 8
What's coming in Java EE 8What's coming in Java EE 8
What's coming in Java EE 8David Delabassee
 
Configure Your Projects with Apache Tamaya
Configure Your Projects with Apache TamayaConfigure Your Projects with Apache Tamaya
Configure Your Projects with Apache TamayaAnatole Tresch
 
Oracle Keynote from JMagghreb 2014
Oracle Keynote from JMagghreb 2014Oracle Keynote from JMagghreb 2014
Oracle Keynote from JMagghreb 2014Simon Ritter
 
Java: Create The Future Keynote
Java: Create The Future KeynoteJava: Create The Future Keynote
Java: Create The Future KeynoteSimon Ritter
 
Adopt-a-JSR for JSON Processing 1.1, JSR 374
Adopt-a-JSR for JSON Processing 1.1, JSR 374Adopt-a-JSR for JSON Processing 1.1, JSR 374
Adopt-a-JSR for JSON Processing 1.1, JSR 374Heather VanCura
 
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
 
Bytecode Verification, the Hero That Java Needs [JavaOne 2016 CON1500]
Bytecode Verification, the Hero That Java Needs [JavaOne 2016 CON1500]Bytecode Verification, the Hero That Java Needs [JavaOne 2016 CON1500]
Bytecode Verification, the Hero That Java Needs [JavaOne 2016 CON1500]David Buck
 
Java EE 8 Overview (Japanese)
Java EE 8 Overview (Japanese)Java EE 8 Overview (Japanese)
Java EE 8 Overview (Japanese)Logico
 
Practical RESTful Persistence
Practical RESTful PersistencePractical RESTful Persistence
Practical RESTful PersistenceShaun Smith
 
Node.js und die Oracle-Datenbank
Node.js und die Oracle-DatenbankNode.js und die Oracle-Datenbank
Node.js und die Oracle-DatenbankCarsten Czarski
 
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
 
Visualizing and Analyzing GC Logs with R
Visualizing and Analyzing GC Logs with RVisualizing and Analyzing GC Logs with R
Visualizing and Analyzing GC Logs with RPoonam Bajaj Parhar
 
Functional programming with_jdk8-s_ritter
Functional programming with_jdk8-s_ritterFunctional programming with_jdk8-s_ritter
Functional programming with_jdk8-s_ritterSimon Ritter
 
Modularization With Project Jigsaw in JDK 9
Modularization With Project Jigsaw in JDK 9Modularization With Project Jigsaw in JDK 9
Modularization With Project Jigsaw in JDK 9Simon Ritter
 
JAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX London
JAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX LondonJAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX London
JAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX LondonArun Gupta
 

Was ist angesagt? (20)

JSONB introduction and comparison with other frameworks
JSONB introduction and comparison with other frameworksJSONB introduction and comparison with other frameworks
JSONB introduction and comparison with other frameworks
 
Configuration with Apache Tamaya
Configuration with Apache TamayaConfiguration with Apache Tamaya
Configuration with Apache Tamaya
 
What's coming in Java EE 8
What's coming in Java EE 8What's coming in Java EE 8
What's coming in Java EE 8
 
Configure Your Projects with Apache Tamaya
Configure Your Projects with Apache TamayaConfigure Your Projects with Apache Tamaya
Configure Your Projects with Apache Tamaya
 
Oracle Keynote from JMagghreb 2014
Oracle Keynote from JMagghreb 2014Oracle Keynote from JMagghreb 2014
Oracle Keynote from JMagghreb 2014
 
Java: Create The Future Keynote
Java: Create The Future KeynoteJava: Create The Future Keynote
Java: Create The Future Keynote
 
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ć,...
 
Adopt-a-JSR for JSON Processing 1.1, JSR 374
Adopt-a-JSR for JSON Processing 1.1, JSR 374Adopt-a-JSR for JSON Processing 1.1, JSR 374
Adopt-a-JSR for JSON Processing 1.1, JSR 374
 
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
 
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
 
Bytecode Verification, the Hero That Java Needs [JavaOne 2016 CON1500]
Bytecode Verification, the Hero That Java Needs [JavaOne 2016 CON1500]Bytecode Verification, the Hero That Java Needs [JavaOne 2016 CON1500]
Bytecode Verification, the Hero That Java Needs [JavaOne 2016 CON1500]
 
Java EE 8 Overview (Japanese)
Java EE 8 Overview (Japanese)Java EE 8 Overview (Japanese)
Java EE 8 Overview (Japanese)
 
Practical RESTful Persistence
Practical RESTful PersistencePractical RESTful Persistence
Practical RESTful Persistence
 
Node.js und die Oracle-Datenbank
Node.js und die Oracle-DatenbankNode.js und die Oracle-Datenbank
Node.js und die Oracle-Datenbank
 
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 - HTTP2 Comes to Java! - David Delabassee
JavaCro'15 - HTTP2 Comes to Java! - David DelabasseeJavaCro'15 - HTTP2 Comes to Java! - David Delabassee
JavaCro'15 - HTTP2 Comes to Java! - David Delabassee
 
Visualizing and Analyzing GC Logs with R
Visualizing and Analyzing GC Logs with RVisualizing and Analyzing GC Logs with R
Visualizing and Analyzing GC Logs with R
 
Functional programming with_jdk8-s_ritter
Functional programming with_jdk8-s_ritterFunctional programming with_jdk8-s_ritter
Functional programming with_jdk8-s_ritter
 
Modularization With Project Jigsaw in JDK 9
Modularization With Project Jigsaw in JDK 9Modularization With Project Jigsaw in JDK 9
Modularization With Project Jigsaw in JDK 9
 
JAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX London
JAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX LondonJAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX London
JAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX London
 

Ähnlich wie JSON-B for CZJUG

Java EE 8 Adopt a JSR : JSON-P 1.1 & MVC 1.0
Java EE 8 Adopt a JSR : JSON-P 1.1 & MVC 1.0Java EE 8 Adopt a JSR : JSON-P 1.1 & MVC 1.0
Java EE 8 Adopt a JSR : JSON-P 1.1 & MVC 1.0David Delabassee
 
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
 
JavaOne 2014 Java EE 8 Booth Slides
JavaOne 2014 Java EE 8 Booth SlidesJavaOne 2014 Java EE 8 Booth Slides
JavaOne 2014 Java EE 8 Booth SlidesEdward Burns
 
JavaOne2015フィードバック @ 富山合同勉強会
JavaOne2015フィードバック @ 富山合同勉強会JavaOne2015フィードバック @ 富山合同勉強会
JavaOne2015フィードバック @ 富山合同勉強会Takashi Ito
 
Burns jsf-confess-2015
Burns jsf-confess-2015Burns jsf-confess-2015
Burns jsf-confess-2015Edward Burns
 
20160123 java one2015_feedback @ Osaka
20160123 java one2015_feedback @ Osaka20160123 java one2015_feedback @ Osaka
20160123 java one2015_feedback @ OsakaTakashi Ito
 
What's Coming in Java EE 8
What's Coming in Java EE 8What's Coming in Java EE 8
What's Coming in Java EE 8PT.JUG
 
2015 Java update and roadmap, JUG sevilla
2015  Java update and roadmap, JUG sevilla2015  Java update and roadmap, JUG sevilla
2015 Java update and roadmap, JUG sevillaTrisha Gee
 
Valencia EMEA Java User Group Summit
Valencia EMEA Java User Group SummitValencia EMEA Java User Group Summit
Valencia EMEA Java User Group SummitHeather VanCura
 
Interactive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and ArchitectureInteractive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and ArchitectureJavaDayUA
 
Bringing Java into the Open
Bringing Java into the Open Bringing Java into the Open
Bringing Java into the Open Heather VanCura
 
The State of Java under Oracle at JCertif 2011
The State of Java under Oracle at JCertif 2011The State of Java under Oracle at JCertif 2011
The State of Java under Oracle at JCertif 2011Arun Gupta
 
Change Management for Oracle Database with SQLcl
Change Management for Oracle Database with SQLcl Change Management for Oracle Database with SQLcl
Change Management for Oracle Database with SQLcl Jeff Smith
 
ADBA (Asynchronous Database Access)
ADBA (Asynchronous Database Access)ADBA (Asynchronous Database Access)
ADBA (Asynchronous Database Access)Logico
 
112815 java ee8_davidd
112815 java ee8_davidd112815 java ee8_davidd
112815 java ee8_daviddTakashi Ito
 
Join the Java Evolution GIDS Bangalore & Pune
Join the Java Evolution GIDS Bangalore & PuneJoin the Java Evolution GIDS Bangalore & Pune
Join the Java Evolution GIDS Bangalore & PuneHeather VanCura
 
Module 1: JavaScript Basics
Module 1: JavaScript BasicsModule 1: JavaScript Basics
Module 1: JavaScript BasicsDaniel McGhan
 
Serverless Java - Challenges and Triumphs
Serverless Java - Challenges and TriumphsServerless Java - Challenges and Triumphs
Serverless Java - Challenges and TriumphsDavid Delabassee
 
Advance your Career and Help Define Java’s Future
Advance your Career and Help Define Java’s FutureAdvance your Career and Help Define Java’s Future
Advance your Career and Help Define Java’s FutureHeather VanCura
 

Ähnlich wie JSON-B for CZJUG (20)

Java EE 8 Adopt a JSR : JSON-P 1.1 & MVC 1.0
Java EE 8 Adopt a JSR : JSON-P 1.1 & MVC 1.0Java EE 8 Adopt a JSR : JSON-P 1.1 & MVC 1.0
Java EE 8 Adopt a JSR : JSON-P 1.1 & MVC 1.0
 
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
 
JavaOne 2014 Java EE 8 Booth Slides
JavaOne 2014 Java EE 8 Booth SlidesJavaOne 2014 Java EE 8 Booth Slides
JavaOne 2014 Java EE 8 Booth Slides
 
JavaOne2015フィードバック @ 富山合同勉強会
JavaOne2015フィードバック @ 富山合同勉強会JavaOne2015フィードバック @ 富山合同勉強会
JavaOne2015フィードバック @ 富山合同勉強会
 
Burns jsf-confess-2015
Burns jsf-confess-2015Burns jsf-confess-2015
Burns jsf-confess-2015
 
20160123 java one2015_feedback @ Osaka
20160123 java one2015_feedback @ Osaka20160123 java one2015_feedback @ Osaka
20160123 java one2015_feedback @ Osaka
 
What's Coming in Java EE 8
What's Coming in Java EE 8What's Coming in Java EE 8
What's Coming in Java EE 8
 
2015 Java update and roadmap, JUG sevilla
2015  Java update and roadmap, JUG sevilla2015  Java update and roadmap, JUG sevilla
2015 Java update and roadmap, JUG sevilla
 
Valencia EMEA Java User Group Summit
Valencia EMEA Java User Group SummitValencia EMEA Java User Group Summit
Valencia EMEA Java User Group Summit
 
JDK 10 Java Module System
JDK 10 Java Module SystemJDK 10 Java Module System
JDK 10 Java Module System
 
Interactive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and ArchitectureInteractive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and Architecture
 
Bringing Java into the Open
Bringing Java into the Open Bringing Java into the Open
Bringing Java into the Open
 
The State of Java under Oracle at JCertif 2011
The State of Java under Oracle at JCertif 2011The State of Java under Oracle at JCertif 2011
The State of Java under Oracle at JCertif 2011
 
Change Management for Oracle Database with SQLcl
Change Management for Oracle Database with SQLcl Change Management for Oracle Database with SQLcl
Change Management for Oracle Database with SQLcl
 
ADBA (Asynchronous Database Access)
ADBA (Asynchronous Database Access)ADBA (Asynchronous Database Access)
ADBA (Asynchronous Database Access)
 
112815 java ee8_davidd
112815 java ee8_davidd112815 java ee8_davidd
112815 java ee8_davidd
 
Join the Java Evolution GIDS Bangalore & Pune
Join the Java Evolution GIDS Bangalore & PuneJoin the Java Evolution GIDS Bangalore & Pune
Join the Java Evolution GIDS Bangalore & Pune
 
Module 1: JavaScript Basics
Module 1: JavaScript BasicsModule 1: JavaScript Basics
Module 1: JavaScript Basics
 
Serverless Java - Challenges and Triumphs
Serverless Java - Challenges and TriumphsServerless Java - Challenges and Triumphs
Serverless Java - Challenges and Triumphs
 
Advance your Career and Help Define Java’s Future
Advance your Career and Help Define Java’s FutureAdvance your Career and Help Define Java’s Future
Advance your Career and Help Define Java’s Future
 

Mehr von 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
 
JSON Support in Java EE 8
JSON Support in Java EE 8JSON Support in Java EE 8
JSON Support in Java EE 8Dmitry Kornilov
 

Mehr von 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
 
Introduction to Yasson
Introduction to YassonIntroduction to Yasson
Introduction to Yasson
 
JSON Support in Java EE 8
JSON Support in Java EE 8JSON Support in Java EE 8
JSON Support in Java EE 8
 

Kürzlich hochgeladen

Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 

Kürzlich hochgeladen (20)

Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 

JSON-B for CZJUG

  • 1. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. JSONB introduction and comparison with other frameworks Dmitry Kornilov JSON-B spec lead @m0mus Roman Grigoriadi JSON-B RI lead engineer @bravehorsie
  • 2. Copyright © 2015, 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 © 2015, Oracle and/or its affiliates. All rights reserved. 3 Program Agenda 1. What is JSON-B 2. JSR-367 status 3. Default mapping 4. Customized mapping 5. Demo application 6. JSON-B RI 7. Q&A
  • 4. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 4 • JSON Binding is a standard • It’s about converting Java objects to and from JSON documents • JSON Binding = JSON-B = JSONB = JSR 367 What is JSON Binding? 4
  • 5. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 5 What is JSON Binding? 5 public class Customer { public int id; public String firstName; public String lastName; …. } Customer e = new Customer(); e.id = 1; e.firstName = “John”; e.lastName = “Doe”; { "id": 1, "firstName" : "John", "lastName" : "Doe", } Java JSON
  • 6. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 6 What is JSON Binding? 6 public class Customer { public int id; public String firstName; public String lastName; …. } Customer e = new Customer(); e.id = 1; e.firstName = “John”; e.lastName = “Doe”; { "id": 1, "firstName" : "John", "lastName" : "Doe", } Java JSON JSON-B
  • 7. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 7 • Genson • Gson • Jackson • … Alternatives 7
  • 8. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | JSON-B Standard 8
  • 9. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 99 Java Community Process • JSR-367 • JSR status and updates • Expert group
  • 10. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 1010 Specification and API Project • Hosted on java.net • Spec in pdf format • Git repository • Wiki • Bug tracker • Mailing lists
  • 11. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 1111 Participate! users@jsonb-spec.java.net
  • 12. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 1212 Reference Implementation • eclipselink.org/jsonb • Mirror on GitHub
  • 13. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 1313 Summary • JCP Page https://www.jcp.org/en/jsr/detail?id=367 • Specification Project Home: https://java.net/projects/jsonb-spec • API sources & samples: https://java.net/projects/jsonb-spec/sources/git/show/api • Specification in pdf: https://java.net/projects/jsonb-spec/sources/git/content/spec/spec.pdf • Reference implementation: http://eclipselink.org/jsonb
  • 14. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | JSON-B Default Mapping 14
  • 15. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 1515 Default Mapping • No configuration, no annotations • The scope: – Basic Types – Specific JDK Types – Dates – Classes – Collections/Arrays – Enumerations – JSON-P import javax.json.bind.Jsonb; import javax.json.bind.JsonbBuilder; // Create with default config Jsonb jsonb = JsonbBuilder.create();
  • 16. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. • toJson(…) • fromJson(…) 1616 JSON-B Engine String toJson(Object object); String toJson(Object object, Type runtimeType); void toJson(Object object, Writer writer); void toJson(Object object, Type runtimeType, Writer appendable); void toJson(Object object, OutputStream stream); void toJson(Object object, Type runtimeType, OutputStream stream); <T> T fromJson(String str, Class<T> type); <T> T fromJson(String str, Type runtimeType); <T> T fromJson(Reader readable, Class<T> type); <T> T fromJson(Reader readable, Type runtimeType); <T> T fromJson(InputStream stream, Class<T> type); <T> T fromJson(InputStream stream, Type runtimeType);
  • 17. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 1717 Default Mapping – 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)
  • 18. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 1818 Default Mapping – 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) Serialization: toString() Deserialization: parseXXX()
  • 19. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 1919 • 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) Default Mapping – Basic Types “string” ’u0041’ (byte) 1 (short) 1 (int) 1 1L 1.2f 1.2 true “string” “A” 1 1 1 1 1.2 1.2 true
  • 20. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 2020 Default Mapping – 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
  • 21. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. • java.math.BigInteger • java.math.BigDecimal • java.net.URL • java.net.URI • java.util.Optional • java.util.OptionalInt • java.util.OptionalLong • java.util.OptionalDouble 2121 Default Mapping – Specific Types Serialization: toString() Deserialization: Single argument constructor
  • 22. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 2222 Default Mapping – 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 Serialization: toString() Deserialization: Single argument constructor • Represented by its value if not empty • Considered null if empty
  • 23. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 2323 Optional Types OptionalInt.of(1) OptionalInt.empty() JSON-B 1 Genson {"asInt": 1, "present": true} Gson {”value": 1, "present": true} Jackson 1 JSON-B null Genson - Gson {”value": 0, "present": false} Jackson null
  • 24. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 2424 Default Mapping – Dates 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
  • 25. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 2525 SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy"); Date date = sdf.parse("08.03.2016"); Default Mapping – Date Sample JSON-B “2016-03-08T00:00:00” Genson 1457391600000 Gson "Mar 8, 2016 12:00:00 AM” Jackson 1457391600000
  • 26. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 2626 Default Mapping – Calendar Sample Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(2016, 3, 8); JSON-B “2016-03-08” Genson 1457391600000 Gson {"year":2016, "month":3, "dayOfMonth":8, "hourOfDay":0, "minute":0, "second": 0} Jackson 1457391600000
  • 27. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 2727 Default Mapping – Classes • Public and protected nested and static nested classes • Anonymous classes (serialization only) • Inheritance is supported • Default no-argument constructor is required for deserialization
  • 28. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 2828 Default Mapping – Fields • Final fields are serialized • Static fields are skipped • Transient fields are skipped • Null fields are skipped • Lexicographical order • Parent class fields are serialized before child class fields
  • 29. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 2929 Fields Order Comparison class Parent { public int parentB = 2; public int parentA = 1; } class Child extends Parent { public int childB = 4; public int childA = 3; } JSON-B {"parentA":1,"parentB":2, "childA":3, "childB":4} Genson {"childA":3, "childB":4, "parentA":1,"parentB":2} Gson {"childB":4, "childA":3, "parentB":2,"parentA":1} Jackson {"parentB":2,"parentA":1, "childB":4, "childA":3}
  • 30. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 3030 Default Mapping – Scope and Field Access Strategy 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
  • 31. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 3131 Scope and Field Access Strategy – JSON-B 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 }
  • 32. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 3232 Scope and Field Access Strategy – Genson 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, "publicWithPrivateGetter": 1, "publicNullField": null, "privateWithPublicGetter": 1, "noField": 1 }
  • 33. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 3333 Scope and Field Access Strategy – Gson 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, "privateFinalField": 1, "publicWithNoGetter": 1, "publicWithPrivateGetter": 1, "privateWithNoGetter": 1, "privateWithPublicGetter": 1, }
  • 34. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 3434 Scope and Field Access Strategy – Jackson 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, "publicWithPrivateGetter": 1, "publicNullField": null, "privateWithPublicGetter": 1, "noField": 1 }
  • 35. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 3535 Scope and Field Access Strategy – Summary Framework Respects getters/setters Respects getter/setter visibility Not public fields Virtual fields JSON-B Yes Yes No Yes Genson Yes No No Yes Gson No No Yes No Jackson Yes No No Yes
  • 36. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 3636 // Array int[] intArray = {1, 2, 3}; jsonb.toJson(intArray); // [1,2,3] // Collection Collection<Object> list = new ArrayList<>(); list.add(1); list.add(2); list.add(null); jsonb.toJson(list); // [1,2,null] // Map Map<String, Object> map = new LinkedHashMap<>(); map.put("first", 1); map.put("second", 2); jsonb.toJson(map); // {"first":1,"second":2} 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
  • 37. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 3737 JSON-P Types • javax.json.JsonArray • javax.json.JsonStructure • javax.json.JsonValue • javax.json.JsonPointer • javax.json.JsonString • javax.json.JsonNumber
  • 38. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 3838 JSON-P Types • javax.json.JsonArray • javax.json.JsonStructure • javax.json.JsonValue • javax.json.JsonPointer • javax.json.JsonString • javax.json.JsonNumber Serialization: javax.json.JsonWriter Deserialization: javax.json.JsonReader
  • 39. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 3939 JsonBuilderFactory f = Json.createBuilderFactory(null); JsonObject jsonObject = f.createObjectBuilder() .add(“name", "Jason") .add(“city", "Prague") .build(); JSON-P Sample { "name": "Jason", ”city": ”Prague" }
  • 40. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 4040 JSON-P Types Support in Other Frameworks • Genson: – Support added in JSR353Bundle • Gson – No JSON-P support • Jackson – Support added in JSR353Module
  • 41. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | Customized Mapping 41
  • 42. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 4242 JSON-B Engine Configuration JsonbConfig config = new JsonbConfig() .withFormatting(…) .withNullValues(…) .withEncoding(…) .withStrictIJSON(…) .withPropertyNamingStrategy(…) .withPropertyOrderStrategy(…) .withPropertyVisibilityStrategy(…) .withAdapters(…) .withBinaryDataStrategy(…); Jsonb jsonb = JsonbBuilder.newBuilder() .withConfig(…) .withProvider(…) .build(); • Annotations • Runtime configuration – JsonbConfig – JsonbBuilder
  • 43. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 4343 Customizations • Property names • Property order • Ignoring properties • Null handling • Custom instantiation • Fields visibility • Adapters • Date/Number Formats • Binary Encoding
  • 44. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 4444 Property Name Customization • JSON-B: – @JsonbProperty (Field, Method) • Genson: – @JsonProperty (Field, Method) – Use GensonBuilder().rename() method • Gson: – @SerializedName (Field) • Jackson: – @JsonProperty (Field, Method)
  • 45. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 4545 Custom Mapping - Property Names public class Customer { public int id; public String firstName; } { "id": 1, "firstName": "Jason" }
  • 46. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 4646 Custom Mapping - 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; } } { "id": 1, "name": "Jason" }
  • 47. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 4747 Custom Mapping - Property Names public class Customer { public int id; public String firstName; @JsonbProperty(“getter-name") String getFirstName() { return firstName; } @JsonbProperty(“setter-name") void setFirstName(String str) { this.firstName = str; } } Serialization: { "id": 1, “getter-name": "Jason" } Deserialization: { "id": 1, “setter-name": "Jason" }
  • 48. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 4848 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(…):
  • 49. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. • Genson – GensonBuilder.with(PropertyNameResolver… resolvers) • Gson: – GsonBuilder.setFieldNamingPolicy(FieldNamingPolicy policy) • Jackson – ObjectMapper.setPropertyNamingStrategy(PropertyNamingStrategy pns) 4949 Property Naming Strategy
  • 50. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 5050 Property Order Strategy • Strategies: – LEXICOGRAPHICAL (A-Z) – ANY – REVERSE (Z-A) • Compile Time: – @JsonbPropertyOrder on class • Runtime: – withPropertyOrderStrategy(…) @JsonbPropertyOrder(ANY) public class Foo { public int bar2; public int bar1; }
  • 51. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. • Compile Time: – Transient modifier – @JsonbTransient annotation – PropertyVisibilityStrategy interface – @JsonbVisibility annotation • Runtime: – withPropertyVisibilityStrategy(…) 5151 Ignoring Properties and Visibility Customization public class Foo { public transient int skipped; @JsonbTransient public int alsoSkipped; } @JsonbVisibility(MyStrategy.class) public class Bar { private int field1; private int field2; }
  • 52. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. • Genson – @JsonIgnore annotation – Include(…) and exclude(…) methods in GensonBuilder class • Gson: – @Exposed annotation – ExclusionStrategy interface • Jackson – @JsonIgnore annotation on field – @JsonIgnoreProperties annotation on class – Filters and mix-ins 5252 Ignoring Properties in Other Frameworks
  • 53. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. • Null fields are skipped by default • Compile Time: – @JsonbNillable annotation • Runtime: – JsonbConfig().withNullValues(true) 5353 Null Handling public class Customer { public int id = 1; @JsonbNillable public String name = null; }
  • 54. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 5454 Null Handling in Other Frameworks Framework Serializes nulls by default Null Handling JSON-B No @JsonbNillable Genson Yes GensonBuilder.setSkipNull(true) Gson No GsonBuilder.serializeNulls() Jackson Yes @JsonInclude(JsonInclude.Include.NON_NULL) ObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
  • 55. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 5555 Custom Instantiation 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": 1, "customer": { "id": 2 } }
  • 56. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. • JAXB inspired JsonbAdapter interface • @JsonbTypeAdapter annotation • JsonbConfig().withAdapters(JsonbAdapter… adapters); 5656 Adapters
  • 57. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. • Genson – Converter interface – JAXB adapters support with JAXBBundle • Gson: – TypeAdapter interface • Jackson – External serializers – Mix-In annotations 5757 Adapters in Other Frameworks
  • 58. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 5858 Date/Number Format public class FormatTest { public Date defaultDate; @JsonbDateFormat("dd.MM.yyyy") public Date formattedDate; public BigDecimal defaultNumber; @JsonbNumberFormat(“#0.00") public BigDecimal formattedNumber; } { “defaultDate”: “2015-07-26T23:00:00", “formattedDate”: ”26.07.2015", “defaultNumber": 1.2, “formattedNumber": 1.20 }
  • 59. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | Date/Number Formats in other Frameworks • Genson – @JsonDateFormat annotation – GensonBuilder.setDateFormat(dateFormat) • Gson: – GsonBuilder.setDateFormat • Jackson – @JsonFormat annotation – objectMapper.setDateFormat(myDateFormat);
  • 60. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 6060 Binary Data Encoding • BYTE (default) • BASE_64 • BASE_64_URL JsonbConfig config = new JsonbConfig() .withBinaryDataStrategy(BinaryDataStrategy.BASE_64); Jsonb jsonb = JsonbBuilder.create(config); String json = jsonb.toJson(obj);
  • 61. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 6161 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. • Configuration: withStrictIJSONSerializationCompliance
  • 62. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | JSON-B RI 62
  • 63. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | JSON-B Demo Application • https://github.com/bravehorsie/jsonb-demo.git • Client server web application • Subject is JSON object, constructed and managed in JavaScript • Demonstrates: –Default and customized mappings –@JsonbProperty annotation –Adapters –Virtual properties handling
  • 64. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 6464 JSON-B Demo Model public class Hero { @JsonbProperty("hero_name") private String name; @JsonbProperty("hero_class") private HeroClass heroClass; @JsonbTypeAdapter(ItemsAdapter.class) @JsonbProperty("hero_items") private Map<ItemSlot, Item> items = new HashMap<>(); @JsonbProperty("total_strength") public Long getTotalStrength() { return getTotalStat("strength"); } @JsonbProperty("total_vitality") public Long getTotalVitality() { return getTotalStat("vitality"); } … } public class ItemSlot { private final Long id; // Head, Shoulders, Chest, Boots, etc. private final String name; } public class Item { // Tyrael's might, Butcher's Carver private String name; private List<Stat> stats; ... } public class Stat { // Strength, Vitality private String name; private Integer value; ... }
  • 65. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 6565 JSON-B Demo Servlet @Override protected void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException, IOException { // Unmarshall json to Request object with Hero inside. Request request = jsonb.fromJson(httpRequest.getInputStream(), Request.class); Hero hero = request.getHero(); // Generate combat log and loot. CombatLog combatLog = combatEngine.generateCombatLog(hero); combatEngine.generateLoot(hero); // Marshall our hero back to JSON object. jsonb.toJson(new Response(hero, combatLog), Response.class, httpResponse.getOutputStream()); }
  • 66. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | JSON-B Scope and Concurrency • Thread safe • Optimal when instance is created per “class model” or per configuration. public class MyRestWsDao { private final Jsonb jsonb; public MyRestWsDao() { JsonbBuilder.create(config); } public Response callBusiness(Request req) { String reqPayload = jsonb.toJson(req); String respPayload = transport.send(reqPayload); return jsonb.fromJson( respPayload, Response.class); } }
  • 67. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | Type Resolution and Generics • There is no type info in JSON document. • Type resolution by field / method type declaration { ”fileld1": ”value1", “field2": ”value2” } jsonb.fromJson(json, Pojo.class); public class Pojo { private Box box; }
  • 68. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | Type Resolution and Generics • Generic types are resolved by field bounds // Example 1 private List<Box> boxList; // Example 2 public class Pojo<X> { private GenericPojo<Integer> integerGenericPojo; } public class GenericPojo<X> { private List<X> x; }
  • 69. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | Type Resolution and Generics • Generic types for root type must be passed to JSONB • Deserialization into interfaces is not supported (besides known types as Map, List, Set, etc..) public class GenericBox<X> { private List<X> xList; private X x; } jsonb.fromJson(json, new GenericBox<BigDecimal>() {}.getClass()); public class IncompatibleClass { public Serializable something; }
  • 70. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | JSON-B Adapters • JSON-B runtime conversion of one type to another (in addition to pre- process conversion) • Customizing types, which you can’t modify (don’t own sources) • Conversion is needed for just a part of domain model • Inspired by JAXB XmlAdapter
  • 71. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 7171 JSON-B Adapter Sample public class User { private Long id; private String email; private String userName; private String firstName; private String surName; } { “email”: ”f.pokorny@centrum.cz", “firstName": “Frantisek", “id”: 123, “userName": “frantaUser", “surName”: ”Pokorny" }
  • 72. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 7272 JSON-B Adapter Sample public class AdaptedUser { @JsonbProperty("USER_ID") private Long id; } { “USER_ID”: 123 }
  • 73. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 7373 JSON-B Adapter Sample public class UserAdapter implements JsonbAdapter<User, AdaptedUser> { @Inject private UserService userService; @Override public AdaptedUser adaptToJson(User obj) throws Exception { return new AdaptedUser(obj.getId()); } @Override public User adaptFromJson(AdaptedUser obj) throws Exception { User user = userService.findById(obj.getId()); return user; } }
  • 74. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 7474 JSON-B Adapter Sample public class Hero { ... @JsonbTypeAdapter(ItemsAdapter.class) private Map<ItemSlot, Item> items = new HashMap<>(); ... } public class ItemSlot { private final Long id; private final String name; ... } public class Item { private String name; private List<Stat> stats; ... }
  • 75. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 7575 JSON-B Adapter Sample public class ItemsAdapter implements JsonbAdapter<Map<ItemSlot, Item>, Map<String, Item>> { @Override public Map<String, Item> adaptToJson(Map<ItemSlot, Item> obj) throws Exception { final Map<String, Item> result = new HashMap<>(); for (Map.Entry<ItemSlot, Item> entry : obj.entrySet()) { result.put(entry.getKey().getName(), entry.getValue()); } return result; } @Override public Map<ItemSlot, Item> adaptFromJson(Map<String, Item> obj) throws Exception { final Map<ItemSlot, Item> result = new HashMap<>(); for (Map.Entry<String, Item> entry : obj.entrySet()) { ItemSlotEnum slotEnum = ItemSlotEnum.valueOf(entry.getKey()); result.put(new ItemSlot(slotEnum.getId(), slotEnum.name()), entry.getValue()); } return result; } }
  • 76. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | What’s Next • Serializers / Deserializers with access to low level JSON-P API • Polymorphism (@JsonbPolymorphic / PolymorphicAdapter)
  • 77. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 7777 Participate! users@jsonb-spec.java.net
  • 78. Copyright © 2015, Oracle and/or its affiliates. All rights reserved. | Q&A 78

Hinweis der Redaktion

  1. Here is some legal stuff. What I will present now could be not be included in the final version of the product. So the text basically says that you shouldn't trust me. Trust no one.
  2. I will start with defining and explaining what JSON-B is. After that we will go through JSR status and progress. Next I will show you what is in the spec.
  3. Why do we need a standard?
  4. Native JSON Binding frameworks Not comparing with JAXB inspired frameworks Goal of standardizing. Experts group
  5. OK. Now lets talk about the specification.
  6. Current state – Early Draft
  7. Now it’s time to see what’s in the spec. We will start with default mapping.
  8. The first question comes is what is default mapping? JSONB engine with default mapping sample We go though all these items later
  9. What is JSON-B engine?
  10. Lets take a look how default mapping works. Here is a list of all basic types handled by JSON-B specification. It includes all basic types and the corresponding primitives.
  11. The rules are simple: toString() method is used for serialization and the corresponding parse() method for deserialization.
  12. Here is a sample. All frameworks handle it the same way, so no comparison here.
  13. Specific types. The specific types are JDK types specified in JSON-B spec which are not basic. It includes…
  14. For Big and URL types toString() method is used for serialization the same as for basic types. For deserialization (here comes the difference) default constructor with String argument is used.
  15. Optional types were introduced in Java 8. Optional can be empty or contains a value. If it does have a value it gets represented by it. The value is processed instead of Optional type. If it’s empty it’s precessed as null.
  16. Not all frameworks handle optional types the same way.
  17. Calendar with no time
  18. Calendar with no time portion.
  19. Now lets talk about classes. The specification strictly defines what kind of classes are supported.
  20. Specification is also clear about what types of fields are supported and in which order fields are serialized.
  21. Respect getters/setters Respect getters/setters visibility Respect property visibility Support virtual fields
  22. Jackson has the same results as Genson.
  23. Here is a summary table.
  24. Arrays and Collections. Here is a list of officially supported types. Sample is on the right side. Nothing much to say here. Just important to mention that null elements are not skipped here as in case of class fields and always serialized.
  25. JSON-P types. JSON-P is used by JSON-B as a parser. The following JSON-P types are supported.
  26. The rules are simple. JsonWriter from jsonp is used for serialization and JsonReader for deserialization.
  27. Here is a sample. As you see, JSON-P class is serialized as a normal Java class.
  28. There are Genson and Jackson modules to support JSON-P types. Gson doesn’t have a special JSONP types support. But it can be added by creating a custom serializer there.
  29. This is it about defaults. Now lets talk about how mapping can be customized.
  30. There are 2 types of configuration: Compile type and Runtime. JsonbBuilder.withProvider()
  31. On this slide a summarized all customizations provided by JSONB. Other frameworks do have it as well. Some them offer much more complicated customizations. Lets quickly go throw these customizations in details.
  32. Sometimes we need to have a field name in JSON document different than in Java class. This is a common use case. JSONB offers JsonbProperty annotation to do it. Other frameworks have it the similar way but annotation is named differently.
  33. Here is a sample. We have a Customer class which serializes to this JSON document by default. We want to serialize firstName field as name.
  34. In order to do it we put JsonbProperty on firstName field with different name specified. Alternatively JsonbProperty annotation can be placed on a getter.
  35. We actually can use different property names for serialization and for deserialization as this sample shows. Strange use case, is it?
  36. Property naming strategy is a way to change property names globally. By default field is serialized with a name as it is defined in a class. If this is not a desired behavior JSONB supports 6 predefined strategies or a custom one can be created. Naming strategy is specified at runtime using withPropertyNamingStrategy of JsonbConfig class.
  37. All other frameworks have a similar feature.
  38. ANY - performance
  39. Here is how other frameworks handle ignoring properties.
  40. Different frameworks handle nulls different way. Here is a comparison table.
  41. Sometimes we need to customize a way how class instance is created. For example if class is created by a static factory method instead of a default constructor. In this case this method has to be annotated with JsonbCreator annotation and it will be called to make an instance of a class instead of a default constructor. Parameters are also supported. Take a look at the sample. Order class has a field customer. Customer class has a method annotated with JsonbCreator annotation. During unmarshalling this method is called and ‘two’ is passed as a parameter.
  42. Tokenizers, Readers
  43. All other frameworks have similar features. All of them allow you to define classes with custom logic used to control binding process. Genson actually supports JAXB annotations in JAXBBundle. Jackson has a very powerfull and simple mix-ins mechanism.
  44. Again. All other frameworks have a similar feature.
  45. If binary data is processed it has to be encoded. JSONB supports 3 types of binary encoding: byte, base_64 and base_64_url. Encoding is specified as part of runtime configuration using withBinaryDataStrategy method of JsonbConfig class.
  46. I-JSON (”Internet JSON”) is a restricted profile of JSON. It’s a standard draft. JSON-B fully supports I-JSON by default with three exceptions: It is possible to switch a full support mode in runtime config using withStrictIJSONSerializationCompliance method of JsonbConfig class.
  47. This is it about defaults. Now lets talk about how mapping can be customized.
  48. Deserializer doesn’t know the root type, so it must be passed In case of generic type variables, an extension or anonymous class must be passed to Jsonb. Considering using TypeToken which is popular in other frameworks. If generic variable type cannot be resolved it is treated as Object – HashMap is used to populate it. Interface and abstract types cannot be resolved by default. (with exception to known interfaces like Map/List).
  49. Supposed to be created per “class model” or configuration. JSONP Generator/Parser instances created and closed inside JSONB each toJson / fromJson call
  50. Deserializer doesn’t know the root type, so it must be passed In case of generic type variables, an extension or anonymous class must be passed to Jsonb. Considering using TypeToken which is popular in other frameworks. If generic variable type cannot be resolved it is treated as Object – HashMap is used to populate it. Interface and abstract types cannot be resolved by default. (with exception to known interfaces like Map/List).
  51. Deserializer doesn’t know the root type, so it must be passed In case of generic type variables, an extension or anonymous class must be passed to Jsonb. Considering using TypeToken which is popular in other frameworks. If generic variable type cannot be resolved it is treated as Object – HashMap is used to populate it. Interface and abstract types cannot be resolved by default. (with exception to known interfaces like Map/List).
  52. Deserializer doesn’t know the root type, so it must be passed In case of generic type variables, an extension or anonymous class must be passed to Jsonb. Considering using TypeToken which is popular in other frameworks. If generic variable type cannot be resolved it is treated as Object – HashMap is used to populate it. Interface and abstract types cannot be resolved by default. (with exception to known interfaces like Map/List).
  53. Deserializer doesn’t know the root type, so it must be passed In case of generic type variables, an extension or anonymous class must be passed to Jsonb. Considering using TypeToken which is popular in other frameworks. If generic variable type cannot be resolved it is treated as Object – HashMap is used to populate it. Interface and abstract types cannot be resolved by default. (with exception to known interfaces like Map/List).
  54. Deserializer doesn’t know the root type, so it must be passed In case of generic type variables, an extension or anonymous class must be passed to Jsonb. Considering using TypeToken which is popular in other frameworks. If generic variable type cannot be resolved it is treated as Object – HashMap is used to populate it. Interface and abstract types cannot be resolved by default. (with exception to known interfaces like Map/List).