使用Jackson将包裹式JSON反序列化为User类的最简方法是什么?
Got it, let's walk through the simplest ways to turn your wrapped JSON into a User instance using Jackson. Your JSON has a user wrapper around the actual user data, and we need to skip the extra xx field too—here are two straightforward approaches:
Approach 1: Use @JsonRootName + Root Unwrapping
This method is clean if you want to consistently unwrap the user root object for this class.
First, annotate your User class with @JsonRootName to map it to the top-level user key in the JSON:
import com.fasterxml.jackson.annotation.JsonRootName; @JsonRootName("user") public class User { private String name; // Basic getters and setters (or use Lombok's @Data to auto-generate these) public String getName() { return name; } public void setName(String name) { this.name = name; } }
Then, configure your ObjectMapper to unwrap root values and ignore unknown fields (like xx):
import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class DeserializeExample { public static void main(String[] args) throws Exception { String json = "{ \"xx\": { \"foo\": \"bar\" }, \"user\": { \"name\": \"john\" } }"; ObjectMapper mapper = new ObjectMapper(); // Enable unwrapping of the root object specified by @JsonRootName mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE); // Ignore any extra fields we don't care about (like "xx") mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); User user = mapper.readValue(json, User.class); System.out.println(user.getName()); // Outputs: john } }
Approach 2: Use @JsonSetter with Nested Path (No Global Config)
If you don't want to enable a global deserialization feature, you can directly map the nested user.name field to your User class's name property:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonSetter; @JsonIgnoreProperties(ignoreUnknown = true) // Skip extra fields like "xx" public class User { private String name; // Map the nested "user.name" JSON field directly to this setter @JsonSetter("user.name") public void setName(String name) { this.name = name; } public String getName() { return name; } }
With this setup, you don't need any special ObjectMapper configuration—just use the default:
ObjectMapper mapper = new ObjectMapper(); User user = mapper.readValue(json, User.class);
Both approaches work perfectly for your use case. If you're using Lombok, adding @Data to the User class will replace the manual getters/setters, making the code even more concise.
内容的提问来源于stack exchange,提问作者J. Doe

