Skip to main content

Working with Jackson

Jimmer objects are dynamic and not all properties of an object need to be initialized. It allows missing some properties.

  • Accessing an unspecified property directly in code will cause an exception.

  • Unspecified properties are automatically ignored in JSON serialization without exceptions.

JSON serialization is mentioned here, referring to jackson.

jimmer-core defines a jackson module: org.babyfish.jimmer.jackson.ImmutableModule which can add the ability of serialize/deserialize jimmer immutable objects for jackson.

There are two cases:

  • Using Spring Boot Starter

    In this case, Jimmer has already registered ImmutableModule to Spring as below:

    // Internal Jimmer code, not user code
    @ConditionalOnMissingBean(ImmutableModule.class)
    @Bean
    public ImmutableModule immutableModule() {
    return new ImmutableModule();
    }

    Therefore, the default ObjectMapper of Spring can already serialize/deserialize Jimmer dynamic objects, and most serialization/deserialization work is done automatically by Spring during HTTP interaction, so no extra development is required.

    caution

    The default JSON handling library in Spring is jackson. Don't replace it.

  • Using low level API

    ObjectMapper mapper = new ObjectMapper()
    .registerModule(new ImmutableModule());

    TreeNode treeNode = Immutables.createTreeNode(
    draft -> draft.setName("Root Node")
    );

    // Serialize
    String json = mapper.writeValueAsString(treeNode);

    // Deserialize
    TreeNode deserializedTreeNode =
    mapper.readValue(json, TreeNode.class);
tip
  • For serialization, there is a handy way which is the toString method of jimmer objects.