乐闻世界logo
搜索文章和话题

How can I include raw JSON in an object using Jackson?

1个答案

1

When working with Jackson to process JSON data, there may be cases where it is necessary to preserve a portion of the raw JSON string within a Java object. This is accomplished by applying the @JsonRawValue annotation. The @JsonRawValue annotation instructs Jackson to directly output the annotated field's content as JSON without any additional conversion or encoding.

This approach is particularly useful for scenarios where a small portion of unstructured data needs to be embedded within structured data, such as dynamic properties or configuration items that are already in JSON format and do not require additional conversion.

Example

For instance, consider a User class that contains basic information such as name and age. Additionally, we want to include a raw JSON string within this class to store additional user information, which may change over time.

java
import com.fasterxml.jackson.annotation.JsonRawValue; import com.fasterxml.jackson.databind.ObjectMapper; public class User { private String name; private int age; @JsonRawValue private String additionalInfo; public User(String name, int age, String additionalInfo) { this.name = name; this.age = age; this.additionalInfo = additionalInfo; } // omitting getter and setter methods public static void main(String[] args) throws Exception { User user = new User("Alice", 30, "{\"interests\": [\"Reading\", \"Hiking\"], \"membership\": \"Gold\"}"); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(user); System.out.println(json); } }

In this example, the additionalInfo field is annotated with @JsonRawValue, meaning its content is directly treated as JSON and inserted into the final serialized string. When creating a User object and serializing it, the JSON string contained in additionalInfo is not escaped or modified; it is directly output as part of the JSON.

Output

json
{"name":"Alice","age":30,"additionalInfo":{"interests":["Reading","Hiking"],"membership":"Gold"}}

Note how the additionalInfo field maintains its JSON object format and is not converted into a string.

This approach enables flexible handling of data that may frequently change in structure, without requiring modifications to the data model each time.

2024年8月9日 02:50 回复

你的答案