I want to get some properties as JSON strings in Jackson!

1.First of all

I can easily convert (deserialize) Json string-> Java object in Jackson, but I have a requirement to get some properties as JSON string.

The purpose is to have a magical property (let's call it payload here) that can hold anything, and want to restore it with the data type (FQCN) defined in another property.

Jackson has a @JsonValue that treats JSON strings as they are, but this is only valid for serialization. Unfortunately, this is not the case for deserialization.

The workaround is to implement your own JsonDeserializer and specify the deserialization process individually with @JsonDeserialize. However, since the purpose is "I want to get the JSON string as it is", the implementation of JsonDeserializer is very easy.

2. Source code

JsonRawValueDeserializer.java


package com.example.jacksondemo;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

//★ Point 1
public class JsonRawValueDeserializer extends JsonDeserializer<String> {

    //★ Point 2
    @Override
    public String deserialize(JsonParser parser, DeserializationContext context)
            throws IOException, JsonProcessingException {
        return parser.readValueAsTree().toString();
    }
}

MyModel.java


package com.example.jacksondemo;

import java.io.Serializable;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

public class MyModel implements Serializable {

    private static final long serialVersionUID = 1L;

    //★ Point 3
    // I want json raw text!
    @JsonDeserialize(using = JsonRawValueDeserializer.class)
    private String payload;
    
    // these property are auto mapped by jackson (without special operation)
    private String fqcn;
    private Integer priority;
    private String messageId;

    // constructor, setter, getter omitted
}

** ★ Point 1 ** Inherit the com.fasterxml.jackson.databind.JsonDeserializer class and define your ownJsonDeserializer. For the type parameter, specify the type of the deserialization process result, that is, String this time.

** ★ Point 2 ** Implement to override the deserialize method and return a JSON string.

** ★ Point 3 ** In the Java class that maps JSON, add the @JsonDeserialize annotation to the property whose value you want to map as it is a JSON string. ʻUseattribute ★ Specify the originalJsonDeserializer` implemented in point 1.

Now, even if the JSON payload property is an object, the JSON string will be stored as is in the Stringpayload property. To achieve this goal, look at the dqcn property to identify the data type, and then deserialize the String value of the payload property with the desired data type.

3. Finally

This time, I explained how to get some properties as JSON strings by deserializing Jackson. Jackson has a function called JsonNode that reads Json as tree-structured data, but I think that there are many ways to map Json and Java. At that time, if you find that only a specific property remains Json, please try this usage.

Recommended Posts

I want to get some properties as JSON strings in Jackson!
[jackson] I want to receive JSON values "0" and "1" as boolean
I want to get the value in Ruby
I want to use Combine in UIKit as well.
[Android] I want to get the listener from the button in ListView
I want to use @Autowired in Servlet
How to assemble JSON directly in Jackson
[Note] I want to get in reverse order using afterLast with JdbcTemplate
I want to get the IP address when connecting to Wi-Fi in Java
I want to send an email in Java.
I want to pass APP_HOME to logback in Gradle
rsync4j --I want to touch rsync in Java.
[Xcode] I want to manage images in folders
I want to be eventually even in kotlin
I want to use Clojure's convenient functions in Kotlin
I want to do something like "cls" in Java
I want to embed any TraceId in the log
I want to use fish shell in Laradock too! !!
I want to use ES2015 in Java too! → (´ ・ ω ・ `)
I want to use a little icon in Rails
I want to define a function in Rails Console
I want to stop snake case in table definition
I want to click a GoogleMap pin in RSpec
# 1_JAVA I want to get the index number by specifying one character in the character string.
I want to find the MD5 checksum of a file in Java and get the result as a string in hexadecimal notation.
I want to get along with Map [Java beginner]
[Ruby on Rails] I want to get the URL of the image saved in Active Storage
I want to find a relative path in a situation using Path
I want to set the conditions to be displayed in collection_check_boxes
I want to perform high-speed prime factorization in Ruby (ABC177E)
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
I want to create a Parquet file even in Ruby
I want to transition to the same screen in the saved state
I want to simplify the conditional if-else statement in Java
I want to convert characters ...
[Ruby] I want to put an array in a variable. I want to convert to an array
I want to display the images under assets/images in the production environment
I want to add devise in Rails, but I can't bundle install
I want to remove the top margin in Grouped UITableView (swift)
How to output a list of strings in JSF as comma-separated strings
[Java] I want to perform distinct with the key in the object
I want to change the value of Attribute in Selenium of Ruby
I want to extract between character strings with a regular expression
Swift: I want to chain arrays
I want to use FormObject well
How to get parameters in Spark
I want to convert InputStream to String
I want to docker-compose up Next.js!
How to concatenate strings in java
[Ruby] I want to output only the odd-numbered characters in the character string
[Rails] I want to send data of different models in a form
I want to write JSP in Emacs more easily than the default.
Sample code to serialize and deserialize Java Enum enums and JSON in Jackson
I want to select multiple items with a custom layout in Dialog
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (PowerMockito edition)
(Limited to Java 7 or later) I want you to compare objects in Objects.equals
How to get the current date as a string in yyyyMMdd format
[Ruby] I want to display posted items in order of newest date
I want to display a PDF in Chinese (Korean) with thin reports
My memorandum that I want to make ValidationMessages.properties UTF8 in Spring Boot
I want to display an error message when registering in the database