logo

Jackson

Last Updated: 2023-03-02

Note:

  • Jackson 2.x is under name FasterXML, hosted on GitHub
  • Jackson 1.x is under name codehaus

Be careful if you have both jar in classpath, they may be incompatible

Create ObjectMapper

import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper objectMapper = new ObjectMapper();

// Read
foo = objectMapper.readValue(new File(path), Foo.class);

// Write
objectMapper.writeValue(new File(path), yourObject);

// Write with PrettyPrint
objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(path), foo);

Read/Write with BaseEncoding

Use BaseEncoding in Guava

  • BaseEncoding.base64().encode()
  • BaseEncoding.base64().decode()

E.g.

import com.google.common.io.BaseEncoding;

// Write
String encodedFoo = BaseEncoding.base64().encode(objectMapper.writeValueAsBytes(foo));

// Read
objectMapper.readValue(BaseEncoding.base64().decode(encodedFoo), Foo.class);

Re-parse

objectMapper.readValue(objectMapper.writeValueAsString(foo), Foo.class);

Ignore Unknown Properties

Global level:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Class level:

@JsonIgnoreProperties(ignoreUnknown = true)

Property level:

@JsonIgnore

Error

com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class <your_class_name>]: can not instantiate from JSON object (need to add/enable type information?)

Fix: add empty default constructor to your class.

public MyClass() {}

Generate Schema

Objects:

class Entity {

    private Long id;
    private List<Profile> profiles;

    // getters/setters
}

class Profile {

    private String name;
    private String value;
    // getters / setters
}

Code to generate schema:

import java.io.IOException;
import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.jsonSchema.JsonSchema;
import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper;

public class JacksonProgram {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
        mapper.acceptJsonFormatVisitor(Entity.class, visitor);
        JsonSchema schema = visitor.finalSchema();
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema));
    }
}

Output:

{
  "type": "object",
  "properties": {
    "id": {
      "type": "integer"
    },
    "profiles": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string"
          },
          "value": {
            "type": "string"
          }
        }
      }
    }
  }
}