Download - JSON-B for CZJUG
![Page 1: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/1.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.
JSONB introduction and comparison with other frameworksDmitry KornilovJSON-B spec lead@m0mus
Roman GrigoriadiJSON-B RI lead engineer@bravehorsie
![Page 2: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/2.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Safe Harbor StatementThe following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.
2
![Page 3: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/3.jpg)
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
![Page 4: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/4.jpg)
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 
![Page 5: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/5.jpg)
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
![Page 6: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/6.jpg)
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
![Page 7: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/7.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 7
• Genson• Gson• Jackson• …
Alternatives
7 
![Page 8: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/8.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
JSON-B Standard
8
![Page 9: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/9.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 9 9 
Java Community Process• JSR-367• JSR status and updates• Expert group
![Page 10: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/10.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 10 10
Specification and API Project• Hosted on java.net• Spec in pdf format• Git repository• Wiki• Bug tracker• Mailing lists
![Page 11: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/11.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 11 11
![Page 12: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/12.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 12 12
Reference Implementation• eclipselink.org/jsonb• Mirror on GitHub
![Page 13: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/13.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 13 13
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
![Page 14: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/14.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
JSON-B Default Mapping
14
![Page 15: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/15.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 15 15
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 configJsonb jsonb = JsonbBuilder.create();
![Page 16: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/16.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.
• toJson(…)• fromJson(…)
16 16
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);
![Page 17: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/17.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 17 17
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)
![Page 18: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/18.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 18 18
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()
![Page 19: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/19.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 19 19
• 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) 11L1.2f1.2true
“string”“A”11111.21.2true
![Page 20: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/20.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 20 20
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
![Page 21: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/21.jpg)
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
21 21
Default Mapping – Specific TypesSerialization:toString()
Deserialization:Single argument constructor
![Page 22: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/22.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 22 22
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
![Page 23: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/23.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 23 23
Optional Types
OptionalInt.of(1)
OptionalInt.empty()
JSON-B 1Genson {"asInt": 1, "present": true}
Gson {”value": 1, "present": true}Jackson 1
JSON-B nullGenson -
Gson {”value": 0, "present": false}Jackson null
![Page 24: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/24.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 24 24
Default Mapping – Datesjava.util.Date ISO_DATE_TIME
java.util.Calendar, java.util.GregorianCalendar ISO_DATE if to time information present, otherwise ISO_DATE_TIME
Java.util.TimeZone, java.util.SimpleTimeZone NormalizedCustomId (see TimeZone javadoc)
java.time.Instant ISO_INSTANT
java.time.LocalDate ISO_LOCAL_DATE
java.time.LocalTime ISO_LOCAL_TIME
java.time.LocalDateTime ISO_LOCAL_DATE_TIME
java.time.ZonedDateTime ISO_ZONED_DATE_TIME
java.time.OffsetDateTime ISO_OFFSET_DATE_TIME
java.time.OffsetTime ISO_OFFSET_TIME
java.time.ZoneId NormalizedZoneId as specified in ZoneId javadoc
java.time.ZoneOffset NormalizedZoneId as specified in ZoneOffset javadoc
java.time.Duration ISO 8601 seconds based representation
java.time.Period ISO 8601 period representation
![Page 25: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/25.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 25 25
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");Date date = sdf.parse("08.03.2016");
Default Mapping – Date SampleJSON-B “2016-03-08T00:00:00”Genson 1457391600000
Gson "Mar 8, 2016 12:00:00 AM”Jackson 1457391600000
![Page 26: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/26.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 26 26
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
![Page 27: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/27.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 27 27
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
![Page 28: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/28.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 28 28
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
![Page 29: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/29.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 29 29
Fields Order Comparisonclass 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}
![Page 30: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/30.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 30 30
Default Mapping – Scope and Field Access StrategySerialization• 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
![Page 31: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/31.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 31 31
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}
![Page 32: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/32.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 32 32
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}
![Page 33: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/33.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 33 33
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,}
![Page 34: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/34.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 34 34
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}
![Page 35: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/35.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 35 35
Scope and Field Access Strategy – Summary
Framework Respects getters/setters
Respectsgetter/setter
visibilityNot public fields Virtual fields
JSON-B Yes Yes No YesGenson Yes No No YesGson No No Yes NoJackson Yes No No Yes
![Page 36: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/36.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 36 36
// Arrayint[] intArray = {1, 2, 3};
jsonb.toJson(intArray); // [1,2,3]
// CollectionCollection<Object> list = new ArrayList<>();list.add(1);list.add(2);list.add(null);
jsonb.toJson(list); // [1,2,null]
// MapMap<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
![Page 37: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/37.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 37 37
JSON-P Types• javax.json.JsonArray• javax.json.JsonStructure• javax.json.JsonValue• javax.json.JsonPointer• javax.json.JsonString• javax.json.JsonNumber
![Page 38: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/38.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 38 38
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
![Page 39: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/39.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 39 39
JsonBuilderFactory f = Json.createBuilderFactory(null);
JsonObject jsonObject = f.createObjectBuilder() .add(“name", "Jason") .add(“city", "Prague") .build();
JSON-P Sample
{ "name": "Jason", ”city": ”Prague"}
![Page 40: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/40.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 40 40
JSON-P Types Support in Other Frameworks• Genson:
– Support added in JSR353Bundle
• Gson– No JSON-P support
• Jackson– Support added in JSR353Module
![Page 41: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/41.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Customized Mapping
41
![Page 42: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/42.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 42 42
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
![Page 43: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/43.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 43 43
Customizations• Property names• Property order• Ignoring properties• Null handling• Custom instantiation
• Fields visibility• Adapters• Date/Number Formats• Binary Encoding
![Page 44: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/44.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 44 44
Property Name Customization• JSON-B:
– @JsonbProperty (Field, Method)
• Genson:– @JsonProperty (Field, Method)– Use GensonBuilder().rename() method
• Gson:– @SerializedName (Field)
• Jackson:– @JsonProperty (Field, Method)
![Page 45: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/45.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 45 45
Custom Mapping - Property Namespublic class Customer { public int id; public String firstName;}
{ "id": 1, "firstName": "Jason"}
![Page 46: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/46.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 46 46
Custom Mapping - Property Namespublic class Customer { private int id;
@JsonbProperty("name") private String firstName;}
public class Customer { public int id; public String firstName;
@JsonbProperty("name") public String getFirstName() { return firstName; }}
{ "id": 1, "name": "Jason"}
![Page 47: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/47.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 47 47
Custom Mapping - Property Namespublic 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"}
![Page 48: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/48.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 48 48
Property Naming Strategy• Supported naming strategies
– IDENTITY (myMixedCaseProperty)
– LOWER_CASE_WITH_DASHES (my-mixed-case-property)
– LOWER_CASE_WITH_UNDERSCORES (my_mixed_case_property)
– UPPER_CAMEL_CASE (MyMixedCaseProperty)
– UPPER_CAMEL_CASE_WITH_SPACES (My Mixed Case Property)
– CASE_INSENSITIVE (mYmIxEdCaSePrOpErTy)
– Or a custom implementation
• JsonbConfig().withPropertyNamingStrategy(…):
![Page 49: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/49.jpg)
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)
49 49
Property Naming Strategy
![Page 50: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/50.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 50 50
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;}
![Page 51: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/51.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.
• Compile Time:– Transient modifier– @JsonbTransient annotation– PropertyVisibilityStrategy interface– @JsonbVisibility annotation
• Runtime:– withPropertyVisibilityStrategy(…)
51 51
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;}
![Page 52: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/52.jpg)
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
52 52
Ignoring Properties in Other Frameworks
![Page 53: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/53.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.
• Null fields are skipped by default• Compile Time:
– @JsonbNillable annotation
• Runtime:– JsonbConfig().withNullValues(true)
53 53
Null Handling
public class Customer { public int id = 1;
@JsonbNillable public String name = null;}
![Page 54: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/54.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 54 54
Null Handling in Other Frameworks
FrameworkSerializes 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);
![Page 55: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/55.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 55 55
Custom Instantiationpublic 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 }}
![Page 56: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/56.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.
• JAXB inspired JsonbAdapter interface• @JsonbTypeAdapter annotation• JsonbConfig().withAdapters(JsonbAdapter… adapters);
56 56
Adapters
![Page 57: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/57.jpg)
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
57 57
Adapters in Other Frameworks
![Page 58: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/58.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 58 58
Date/Number Formatpublic 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}
![Page 59: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/59.jpg)
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);
![Page 60: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/60.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 60 60
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);
![Page 61: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/61.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 61 61
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
![Page 62: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/62.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
JSON-B RI
62
![Page 63: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/63.jpg)
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
![Page 64: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/64.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 64 64
JSON-B Demo Modelpublic 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; ...}
![Page 65: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/65.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 65 65
JSON-B Demo Servlet@Overrideprotected 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());}
![Page 66: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/66.jpg)
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); }}
![Page 67: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/67.jpg)
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;}
![Page 68: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/68.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Type Resolution and Generics• Generic types are resolved by field bounds
// Example 1private List<Box> boxList;
// Example 2public class Pojo<X> { private GenericPojo<Integer> integerGenericPojo;}
public class GenericPojo<X> { private List<X> x;}
![Page 69: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/69.jpg)
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;}
![Page 70: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/70.jpg)
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
![Page 71: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/71.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 71 71
JSON-B Adapter Samplepublic class User { private Long id; private String email; private String userName; private String firstName; private String surName;}
{ “email”: ”[email protected]", “firstName": “Frantisek", “id”: 123, “userName": “frantaUser", “surName”: ”Pokorny"}
![Page 72: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/72.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 72 72
JSON-B Adapter Samplepublic class AdaptedUser { @JsonbProperty("USER_ID") private Long id;}
{ “USER_ID”: 123}
![Page 73: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/73.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 73 73
JSON-B Adapter Samplepublic 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; }}
![Page 74: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/74.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 74 74
JSON-B Adapter Samplepublic 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; ...}
![Page 75: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/75.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 75 75
JSON-B Adapter Samplepublic 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; }}
![Page 76: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/76.jpg)
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)
![Page 77: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/77.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. 77 77
![Page 78: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/78.jpg)
Copyright © 2015, Oracle and/or its affiliates. All rights reserved. |
Q&A
78
![Page 79: JSON-B for CZJUG](https://reader036.vdocuments.us/reader036/viewer/2022062523/58ef0e811a28ab754f8b46ab/html5/thumbnails/79.jpg)