SlideShare a Scribd company logo
1 of 18
Simple Jackson w/
DropWizard (& beyond)
Tatu Saloranta
@cowtowncoder
tatu@fasterxml.com
● Assumes some familiarity with JAX-RS/DropWizard
● Jackson is the default DropWizard JSON provider
o … also on: RESTEasy, SpringMVC, Restlet, CXF
● Presentation mostly about data-binding
o reading JSON into Java Objects (POJOs)
o writing Java objects as JSON
● But Jackson offers more: Tree Model (JsonNode),
streaming read/write -- mix’n match!
● Not limited to JSON either (XML, CSV, ...)
Introduction
1. Often “just works”, esp. with bit of practice
2. or with minor adjustments to
a. POJO structure/naming, and/or
b. JSON structure/naming
3. or by using annotations (regular, mix-in)
4. perhaps with changed Jackson defaults
5. using a datatype module (guava, joda)
6. or, using a more dynamic Java representation
a. Tree Model (JsonNode) or “untyped” (Maps of Lists)
7. Rarely if ever need custom handlers! (last resort)
Simple Usage: Claims
● W/ default settings, Jackson reads JSON
a. No-argument constructor (any visibility)
b. Setter (“setValue(x)”) with any visibility (even
private), OR
c. public field of same name (“value”)
● W/ default settings, Jackson writes JSON
a. Public getter (“getValue()”), OR
b. public field of same name (“value”)
Simple Usage: Just Works
// traditional Bean
public class Point {
private int x, y;
public Point() { }
public int getX() {
return x;
}
public void setX(int x){
this.x = x;
}
// and same for ‘y’
}
Simple Usage: Just Works, 2
// or just:
public class Point {
public int x, y;
}
=>{ “x”:100, “y”:200 }
● recursively (nested POJOs)
● for all common JDK types
o Maps, Collections, arrays
o Date/Calendar
o binary (byte[]) as base64
● Visibility rules, naming convention
configurable (default, per-class)
● Result of introspection, annotations is a
logical “Bean” type definition, with
a. “Creator” to use (default ctor, or creator)
b. Type, possibly polymorphic
c. Set of properties w/ accessors (getter/setter/field)
d. Filtering, type id/object id handler etc etc
Simple Usage: Just Works, 3
Sometimes default mapping not compatible:
● Naming not following bean style (C-style etc), or
individual properties “misnamed”
● Inadequate visibility (protected getters)
● No default constructor (can just add private one)
● Not all properties should be written in JSON
● All of above changeable via annotations too; but
sometimes simpler to just change class itself
Simple usage: Changing POJOs
● While ‘ON’ stands for ‘Object Notation’:
o JSON structures that do NOT map nicely;
especially union types (“String or Array”)
o does NOT support basic Object properties:
 Type metadata (no classes)
 Object identity
o multiple ways to express types, object identity:
choice has big effect (Jackson supports many)
● Mapping means fitting _both_ sides
Simple usage: Changing JSON
● @JsonProperty
o indicate inclusion, optionally different name
● @JsonIgnore
o indicate exclusion; either whole property, or just
accessor (if also @JsonProperty)
● @JsonPropertyOrder
o order of JSON properties has no semantics; but
sometimes nice to define output ordering
Simple usage: Annotations
● @JsonCreator (for arg-taking constructor)
o delegating (“first bind as X, give to my
constructor”) or property-based
● @JsonValue for scalar types (most often)
Simple usage: Annotations
public class MyTimeType {
@JsonValue
public String asString() { … }
}
@JsonIgnoreProperties(ignoreUnknown=true)
public class POJO
{
@JsonProperty(“name”)
private final String strName;
@JsonCreator // property-based (named properties)
protected POJO(@JsonProperty(“name”) String name) {
this.name = name;
}
@JsonIgnore
public String getInternalState() { … }
}
Simple usage: Annotation example
● Simple idea: associate, don’t embed!
o no need to modify target class, or bytecode
● Define an interface, (abstract) class with annotations
● Associate source class with target:
o mapper.addMixInAnnotations(target, source);
● Same as if ‘target’ had annotations that ‘source’ has,
from Jackson perspective
See http://www.cowtowncoder.com/blog/archives/2009/08/entry_305.html
for more detailed description.
Simple usage: mix-in annotations
● Visibility for introspection (hide/expose)
o mapper.setVisibility() (per accessor type)
o annotation: @JsonAutoDetect
o convenience vs. security
● Naming convention
o mapper.setPropertyNamingStrategy(x)
o annotation: @JsonNaming
o 3 standard implementations
(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_W
Simple usage: Jackson defaults
● For reading JSON, DeserializationFeature
o ACCEPT_SINGLE_VALUE_AS_ARRAY
o FAIL_ON_UNKNOWN_PROPERTIES
o USE_BIG_DECIMAL_FOR_FLOATS
● For writing JSON, SerializationFeature
o FAIL_ON_EMPTY_BEANS
o INDENT_OUTPUT
o WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED
● mapper.enable(...) / disable(...)
Simple usage: Jackson defaults
But someone may already have solved your
problem!
Datatype modules exist for these and more:
● Guava
● Hibernate
● High-Performance Primitive Collection (HPPC)
● Joda
See: https://github.com/FasterXML/jackson
Simple usage: datatype modules
● If structure (too)
dynamic, difficult to
match with POJO, or
o you just want a tiny
sliver, or you
o like JSON Pointer
● JsonNode similar to
XML DOM, ObjectNode
of json.org
Simple usage: go loose with Trees
JsonNode n = mapper.readTree(src);
String firstName = n
.path(“name”)
.path(“first”).asText();
// or with JSON Pointer:
String fn = n.at(“/name/first”)
.asText();
for (JsonNode child:
n.path(“children”)) {
int age = child.path(“age”).asInt
}
● Not either or choice: can go back & forth:
Person person = mapper.treeToValue(root,
Person.class);
JsonNode childNode = mapper.valueToTree(
person.getChildren().get(0));
● Jackson can read/write JsonNodes just like POJOs;
even have JsonNode-valued properties.
Simple usage: Trees, 2
That’s All, Folks! Questions?
Visit Jackson home at
https://github.com/FasterXML/jackson
and/or join mailing lists at
https://groups.google.com/forum/#!forum/jack
son-user
Simple usage: in closing

More Related Content

What's hot

C# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XMLC# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XMLMohammad Shaker
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
Native XML processing in C++ (BoostCon'11)
Native XML processing in C++ (BoostCon'11)Native XML processing in C++ (BoostCon'11)
Native XML processing in C++ (BoostCon'11)Sumant Tambe
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scalaRuslan Shevchenko
 
Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Ramamohan Chokkam
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript BasicsMindfire Solutions
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptWalid Ashraf
 
JavaScript objects and functions
JavaScript objects and functionsJavaScript objects and functions
JavaScript objects and functionsVictor Verhaagen
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJWORKS powered by Ordina
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOMJalpesh Vasa
 
Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02Ramamohan Chokkam
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic FunctionsWebStackAcademy
 
Textual Modeling Framework Xtext
Textual Modeling Framework XtextTextual Modeling Framework Xtext
Textual Modeling Framework XtextSebastian Zarnekow
 

What's hot (20)

Ajax
AjaxAjax
Ajax
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
C# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XMLC# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XML
 
Week3
Week3Week3
Week3
 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
Native XML processing in C++ (BoostCon'11)
Native XML processing in C++ (BoostCon'11)Native XML processing in C++ (BoostCon'11)
Native XML processing in C++ (BoostCon'11)
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scala
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
JavaScript objects and functions
JavaScript objects and functionsJavaScript objects and functions
JavaScript objects and functions
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
Json the-x-in-ajax1588
Json the-x-in-ajax1588Json the-x-in-ajax1588
Json the-x-in-ajax1588
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOM
 
Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
Java and XML
Java and XMLJava and XML
Java and XML
 
Textual Modeling Framework Xtext
Textual Modeling Framework XtextTextual Modeling Framework Xtext
Textual Modeling Framework Xtext
 

Similar to Simple Jackson with DropWizard

Action Jackson! Effective JSON processing in Spring Boot Applications
Action Jackson! Effective JSON processing in Spring Boot ApplicationsAction Jackson! Effective JSON processing in Spring Boot Applications
Action Jackson! Effective JSON processing in Spring Boot ApplicationsJoris Kuipers
 
Declarative Development Using Annotations In PHP
Declarative Development Using Annotations In PHPDeclarative Development Using Annotations In PHP
Declarative Development Using Annotations In PHPStephan Schmidt
 
Declarative Development Using Annotations In PHP
Declarative Development Using Annotations In PHPDeclarative Development Using Annotations In PHP
Declarative Development Using Annotations In PHPstubbles
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developementfrwebhelp
 
Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012Timo Westkämper
 
Json in Postgres - the Roadmap
 Json in Postgres - the Roadmap Json in Postgres - the Roadmap
Json in Postgres - the RoadmapEDB
 
Java Development with MongoDB
Java Development with MongoDBJava Development with MongoDB
Java Development with MongoDBScott Hernandez
 
JEST: REST on OpenJPA
JEST: REST on OpenJPAJEST: REST on OpenJPA
JEST: REST on OpenJPAPinaki Poddar
 
JSON Data Parsing in Snowflake (By Faysal Shaarani)
JSON Data Parsing in Snowflake (By Faysal Shaarani)JSON Data Parsing in Snowflake (By Faysal Shaarani)
JSON Data Parsing in Snowflake (By Faysal Shaarani)Faysal Shaarani (MBA)
 
LF_APIStrat17_Embracing JSON Schema
LF_APIStrat17_Embracing JSON SchemaLF_APIStrat17_Embracing JSON Schema
LF_APIStrat17_Embracing JSON SchemaLF_APIStrat
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesecosio GmbH
 
Javascript Ks
Javascript KsJavascript Ks
Javascript Ksssetem
 
Basics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examplesBasics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examplesSanjeev Kumar Jaiswal
 
Andrew Dunstan 9.3 JSON Presentation @ Postgres Open 2013
Andrew Dunstan 9.3 JSON Presentation @ Postgres Open 2013Andrew Dunstan 9.3 JSON Presentation @ Postgres Open 2013
Andrew Dunstan 9.3 JSON Presentation @ Postgres Open 2013PostgresOpen
 
PostgreSQL 9.3 and JSON - talk at PgOpen 2013
PostgreSQL 9.3 and JSON - talk at PgOpen 2013PostgreSQL 9.3 and JSON - talk at PgOpen 2013
PostgreSQL 9.3 and JSON - talk at PgOpen 2013Andrew Dunstan
 
03 Object Relational Mapping
03 Object Relational Mapping03 Object Relational Mapping
03 Object Relational MappingRanjan Kumar
 

Similar to Simple Jackson with DropWizard (20)

Action Jackson! Effective JSON processing in Spring Boot Applications
Action Jackson! Effective JSON processing in Spring Boot ApplicationsAction Jackson! Effective JSON processing in Spring Boot Applications
Action Jackson! Effective JSON processing in Spring Boot Applications
 
Declarative Development Using Annotations In PHP
Declarative Development Using Annotations In PHPDeclarative Development Using Annotations In PHP
Declarative Development Using Annotations In PHP
 
Declarative Development Using Annotations In PHP
Declarative Development Using Annotations In PHPDeclarative Development Using Annotations In PHP
Declarative Development Using Annotations In PHP
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
 
Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012
 
Json in Postgres - the Roadmap
 Json in Postgres - the Roadmap Json in Postgres - the Roadmap
Json in Postgres - the Roadmap
 
json
jsonjson
json
 
Java Development with MongoDB
Java Development with MongoDBJava Development with MongoDB
Java Development with MongoDB
 
JEST: REST on OpenJPA
JEST: REST on OpenJPAJEST: REST on OpenJPA
JEST: REST on OpenJPA
 
JSON Data Parsing in Snowflake (By Faysal Shaarani)
JSON Data Parsing in Snowflake (By Faysal Shaarani)JSON Data Parsing in Snowflake (By Faysal Shaarani)
JSON Data Parsing in Snowflake (By Faysal Shaarani)
 
LF_APIStrat17_Embracing JSON Schema
LF_APIStrat17_Embracing JSON SchemaLF_APIStrat17_Embracing JSON Schema
LF_APIStrat17_Embracing JSON Schema
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
9.4json
9.4json9.4json
9.4json
 
Java beans
Java beansJava beans
Java beans
 
Javascript Ks
Javascript KsJavascript Ks
Javascript Ks
 
droidparts
droidpartsdroidparts
droidparts
 
Basics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examplesBasics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examples
 
Andrew Dunstan 9.3 JSON Presentation @ Postgres Open 2013
Andrew Dunstan 9.3 JSON Presentation @ Postgres Open 2013Andrew Dunstan 9.3 JSON Presentation @ Postgres Open 2013
Andrew Dunstan 9.3 JSON Presentation @ Postgres Open 2013
 
PostgreSQL 9.3 and JSON - talk at PgOpen 2013
PostgreSQL 9.3 and JSON - talk at PgOpen 2013PostgreSQL 9.3 and JSON - talk at PgOpen 2013
PostgreSQL 9.3 and JSON - talk at PgOpen 2013
 
03 Object Relational Mapping
03 Object Relational Mapping03 Object Relational Mapping
03 Object Relational Mapping
 

Recently uploaded

Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
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
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
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
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
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
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
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
 

Recently uploaded (20)

Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
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
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
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
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
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)
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
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
 

Simple Jackson with DropWizard

  • 1. Simple Jackson w/ DropWizard (& beyond) Tatu Saloranta @cowtowncoder tatu@fasterxml.com
  • 2. ● Assumes some familiarity with JAX-RS/DropWizard ● Jackson is the default DropWizard JSON provider o … also on: RESTEasy, SpringMVC, Restlet, CXF ● Presentation mostly about data-binding o reading JSON into Java Objects (POJOs) o writing Java objects as JSON ● But Jackson offers more: Tree Model (JsonNode), streaming read/write -- mix’n match! ● Not limited to JSON either (XML, CSV, ...) Introduction
  • 3. 1. Often “just works”, esp. with bit of practice 2. or with minor adjustments to a. POJO structure/naming, and/or b. JSON structure/naming 3. or by using annotations (regular, mix-in) 4. perhaps with changed Jackson defaults 5. using a datatype module (guava, joda) 6. or, using a more dynamic Java representation a. Tree Model (JsonNode) or “untyped” (Maps of Lists) 7. Rarely if ever need custom handlers! (last resort) Simple Usage: Claims
  • 4. ● W/ default settings, Jackson reads JSON a. No-argument constructor (any visibility) b. Setter (“setValue(x)”) with any visibility (even private), OR c. public field of same name (“value”) ● W/ default settings, Jackson writes JSON a. Public getter (“getValue()”), OR b. public field of same name (“value”) Simple Usage: Just Works
  • 5. // traditional Bean public class Point { private int x, y; public Point() { } public int getX() { return x; } public void setX(int x){ this.x = x; } // and same for ‘y’ } Simple Usage: Just Works, 2 // or just: public class Point { public int x, y; } =>{ “x”:100, “y”:200 } ● recursively (nested POJOs) ● for all common JDK types o Maps, Collections, arrays o Date/Calendar o binary (byte[]) as base64
  • 6. ● Visibility rules, naming convention configurable (default, per-class) ● Result of introspection, annotations is a logical “Bean” type definition, with a. “Creator” to use (default ctor, or creator) b. Type, possibly polymorphic c. Set of properties w/ accessors (getter/setter/field) d. Filtering, type id/object id handler etc etc Simple Usage: Just Works, 3
  • 7. Sometimes default mapping not compatible: ● Naming not following bean style (C-style etc), or individual properties “misnamed” ● Inadequate visibility (protected getters) ● No default constructor (can just add private one) ● Not all properties should be written in JSON ● All of above changeable via annotations too; but sometimes simpler to just change class itself Simple usage: Changing POJOs
  • 8. ● While ‘ON’ stands for ‘Object Notation’: o JSON structures that do NOT map nicely; especially union types (“String or Array”) o does NOT support basic Object properties:  Type metadata (no classes)  Object identity o multiple ways to express types, object identity: choice has big effect (Jackson supports many) ● Mapping means fitting _both_ sides Simple usage: Changing JSON
  • 9. ● @JsonProperty o indicate inclusion, optionally different name ● @JsonIgnore o indicate exclusion; either whole property, or just accessor (if also @JsonProperty) ● @JsonPropertyOrder o order of JSON properties has no semantics; but sometimes nice to define output ordering Simple usage: Annotations
  • 10. ● @JsonCreator (for arg-taking constructor) o delegating (“first bind as X, give to my constructor”) or property-based ● @JsonValue for scalar types (most often) Simple usage: Annotations public class MyTimeType { @JsonValue public String asString() { … } }
  • 11. @JsonIgnoreProperties(ignoreUnknown=true) public class POJO { @JsonProperty(“name”) private final String strName; @JsonCreator // property-based (named properties) protected POJO(@JsonProperty(“name”) String name) { this.name = name; } @JsonIgnore public String getInternalState() { … } } Simple usage: Annotation example
  • 12. ● Simple idea: associate, don’t embed! o no need to modify target class, or bytecode ● Define an interface, (abstract) class with annotations ● Associate source class with target: o mapper.addMixInAnnotations(target, source); ● Same as if ‘target’ had annotations that ‘source’ has, from Jackson perspective See http://www.cowtowncoder.com/blog/archives/2009/08/entry_305.html for more detailed description. Simple usage: mix-in annotations
  • 13. ● Visibility for introspection (hide/expose) o mapper.setVisibility() (per accessor type) o annotation: @JsonAutoDetect o convenience vs. security ● Naming convention o mapper.setPropertyNamingStrategy(x) o annotation: @JsonNaming o 3 standard implementations (PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_W Simple usage: Jackson defaults
  • 14. ● For reading JSON, DeserializationFeature o ACCEPT_SINGLE_VALUE_AS_ARRAY o FAIL_ON_UNKNOWN_PROPERTIES o USE_BIG_DECIMAL_FOR_FLOATS ● For writing JSON, SerializationFeature o FAIL_ON_EMPTY_BEANS o INDENT_OUTPUT o WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED ● mapper.enable(...) / disable(...) Simple usage: Jackson defaults
  • 15. But someone may already have solved your problem! Datatype modules exist for these and more: ● Guava ● Hibernate ● High-Performance Primitive Collection (HPPC) ● Joda See: https://github.com/FasterXML/jackson Simple usage: datatype modules
  • 16. ● If structure (too) dynamic, difficult to match with POJO, or o you just want a tiny sliver, or you o like JSON Pointer ● JsonNode similar to XML DOM, ObjectNode of json.org Simple usage: go loose with Trees JsonNode n = mapper.readTree(src); String firstName = n .path(“name”) .path(“first”).asText(); // or with JSON Pointer: String fn = n.at(“/name/first”) .asText(); for (JsonNode child: n.path(“children”)) { int age = child.path(“age”).asInt }
  • 17. ● Not either or choice: can go back & forth: Person person = mapper.treeToValue(root, Person.class); JsonNode childNode = mapper.valueToTree( person.getChildren().get(0)); ● Jackson can read/write JsonNodes just like POJOs; even have JsonNode-valued properties. Simple usage: Trees, 2
  • 18. That’s All, Folks! Questions? Visit Jackson home at https://github.com/FasterXML/jackson and/or join mailing lists at https://groups.google.com/forum/#!forum/jack son-user Simple usage: in closing