Top Banner
14

Jackson cookbook

Apr 14, 2015

Download

Documents

vevaradh

Jackson Cookbook
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Jackson cookbook
Page 2: Jackson cookbook

The Jackson Cookbook

JSON Recipes in Java

©2012 Ted M. Young

This version was published on 2012-08-28

This is a Leanpub book, for sale at:

http://leanpub.com/jacksoncookbook

Leanpub helps authors to self-publish in-progress ebooks. We call this idea Lean Publishing. Tolearn more about Lean Publishing, go to: http://leanpub.com/manifesto

To learn more about Leanpub, go to: http://leanpub.com

Page 3: Jackson cookbook

Tweet This Book!Please help Ted M. Young by spreading the word about this book on Twitter!

The suggested hashtag for this book is #jacksoncookbook.

Find out what other people are saying about the book by clicking on this link to search for thishashtag on Twitter:

https://twitter.com/search/#jacksoncookbook

Page 4: Jackson cookbook

Contents

Acknowledgments i

Introduction i

Problems Welcome! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i

Configuring ObjectMapper 1

Making JSON Output More Readable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Suppressing null values globally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

Appendix: JSON Information 5

JSON Defined . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

Appendix: JSON Tools 6

JSONLint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

JSON Editor Online . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

JSON2HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

Page 5: Jackson cookbook

AcknowledgmentsThanks to Tatu Saloranta for creating Jackson and being so responsive to questions on the Jacksonforum. You can find information about him at his Cowtown Coder¹ blog.

Also, thanks to the LeanPub² folks (Scott, Peter, and Len) for being so responsive to requests andbug reports.

¹http://cowtowncoder.com/author-cowtowncoder.html²https://leanpub.com

i

Page 6: Jackson cookbook

IntroductionJackson is a popular, high-performance JSON processor for Java. Jackson can support almost anyJSON need that you might have, but that flexibility can make it complex to use. This book takesa problem and then shows, with lots of code and JSON examples, how to solve that problem usingvarious Jackson features. Many of these problems were ones I encountered integrating JSON supportwith a “legacy” codebase, i.e., a codebase where I couldn’t modify the code, using Data Binding, butI’ll also cover some of the Streaming API that’s used within custom serializers/deserializers. As abonus, the Appendix contains a description of JSON tools that I’ve found useful along the way.

Problems Welcome!

If you’re using Jackson, and have a pesky problem (or solution!), don’t hesitate to post it in the bookdiscussion group³ and I may include it in the next release of this book.

Jackson Version:

Note that this book covers only the 2.x version of Jackson, not the earlier 1.x releases (2.x is thefuture!).

³https://groups.google.com/forum/#!forum/jackson-cookbook-discuss

i

Page 7: Jackson cookbook

Configuring ObjectMapperThis section covers customizing the serialization/deserialization of your object graph at a globallevel, i.e., per instance of ObjectMapper.

Making JSON Output More Readable

The ObjectMapper is the main class that you’ll use to write out (serialize) an object graph as JSON.By default, the ObjectMapper (really the underlying ObjectWriter) will not put any whitespace inthe generated JSON output. For example:

..

Note: The actual JSON doesn’t have newlines, but I’m wrapping the lines hereso you can see all of it.

{"title":"The Jackson Cookbook","subtitle":"JSON Recipes in Java",

"author":{"name":{"first":"Ted","middle":"M","last":"Young"},

"twitterId":"@jitterted","website":"http://about.me/tedmyoung"},

"url":"https://leanpub.com/jacksoncookbook","language":"English",

"version":"0.1"}

To make the JSON easier to read, you can tell ObjectMapper to use a “pretty printer”, which willinsert spaces and newlines into the output (line 3 tells the mapper to use the default pretty printer):

1 Book jacksonCookbook = new JacksonCookbook();

2 String json = objectMapper

3 .writerWithDefaultPrettyPrinter()

4 .writeValueAsString(jacksonCookbook);

5 System.out.println(json);

The result will be:

{

"title" : "The Jackson Cookbook",

"subtitle" : "JSON Recipes in Java",

"author" : {

"name" : {

"first" : "Ted",

1

Page 8: Jackson cookbook

Configuring ObjectMapper 2

"middle" : "M",

"last" : "Young"

},

"twitterId" : "@jitterted",

"website" : "http://about.me/tedmyoung"

},

"url" : "https://leanpub.com/jacksoncookbook",

"language" : "English",

"version" : "0.1"

}

If you don’t like the way the default pretty printer works, e.g., you don’t want a space beforethe colon, only after (which is a common alternative format), then you’ll need to create a customimplementation of the PrettyPrinter interface. For a minor modification like this, you can subclassthe DefaultPrettyPrinter class and override the method that writes out the name and value fieldsas follows:

1 package com.jitterpig.jacksoncookbook;

2

3 import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;

4

5 public class ModifiedPrettyPrinter extends DefaultPrettyPrinter {

6 @Override

7 public void writeObjectFieldValueSeparator(JsonGenerator jg)

8 throws IOException {

9 if (_spacesInObjectEntries) {

10 jg.writeRaw(": ");

11 } else {

12 jg.writeRaw(':');

13 }

14 }

15 }

The code above was copied from the DefaultPrettyPrinter’s implementation of this method, withthe only change in line 10 where I removed the space before the colon.

To use this, pass an instance of the pretty printer to the mapper: line 4 below is using an instance ofmy ModifiedPrettyPrinter.

1 PrettyPrinter prettyPrinter = new ModifiedPrettyPrinter()

2 Book jacksonCookbook = new JacksonCookbook();

3 String json = objectMapper

Page 9: Jackson cookbook

Configuring ObjectMapper 3

4 .writer(prettyPrinter)

5 .writeValueAsString(jacksonCookbook);

6 System.out.println(json);

The output from the ModifiedPrettyPrinter looks like this:

{

"title": "The Jackson Cookbook",

"subtitle": "JSON Recipes in Java",

"author": {

"name": {

"first": "Ted",

"middle": "M",

"last": "Young"

},

"twitterId": "@jitterted",

"website": "http://about.me/tedmyoung"

},

"url": "https://leanpub.com/jacksoncookbook",

"language": "English",

"version": "0.1"

}

You can also subclass the compact or minimal pretty printer (i.e., the one that’s used if you don’tspecify otherwise) by extending the MinimalPrettyPrinter class. If you want to make moresubstantial changes to how the JSON is formatted, you may want to implement the PrettyPrinterinterface directly. However, I haven’t come across the need to do that.

Page 10: Jackson cookbook

Configuring ObjectMapper 4

Suppressing null values globally

If you have properties that can be null, but don’t want them serialized when they’re null, you cando the following:

objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

This is similar to the @JsonInclude annotation (e.g.,

@JsonSerialize(include = Inclusion.NON_NULL)

placed at the top of a class), but applies the inclusion to all types that are serialized using the sameObjectMapper instance.

Options for this value are:

• ALWAYS - the default, which means all properties are serialized. This is the default.

• NON_NULL - as used above: only non-null properties are serialized.

• NON_DEFAULT - only serializes properties if they differ from the defaults for that object. Defaultsare the values of properties when insantiated using the no-argument constructor. Note thatthis applies to arrays as well.

– This is useful for saving bandwidth: if the defaults are the same on both sides of theserialization, there’s no point in serializing that information.

• NON_EMPTY - only serializes properties that are not “empty”, where empty includes null as wellas:

– Arrays: length is 0

– Collections: isEmpty() is true (i.e., for Map, Lists, etc.)

– Date: the time stamp is 0

– String: length is 0

Page 11: Jackson cookbook

Appendix: JSON InformationJSON Defined

The JSON “standard” is defined on this web site, with the syntax clearly defined.

5

Page 12: Jackson cookbook

Appendix: JSON ToolsJSONLint

Checks that your JSON is valid. If not, it points out where the problem is.

What happens if you forget an opening curly brace

6

Page 13: Jackson cookbook

Appendix: JSON Tools 7

JSON Editor Online

A hierarchical JSON editor.

I used this to create the JSON for this book’s cover

Page 14: Jackson cookbook

Appendix: JSON Tools 8

JSON2HTML

Renders your JSON as text in nested boxes. A nice way to view your JSON data.

Some JSON rendered by JSON2HTML