如何用Jackson从嵌套JSON对象映射字段至Java实体类?
Documents class using annotations from popular JSON processing libraries like Jackson or Gson. Here's how to do it with the most common options: Using Jackson (Spring's default JSON library)
Jackson supports mapping nested JSON fields directly to flat class properties using dot notation in the @JsonProperty annotation. Since you're already using Lombok's @Data, this works seamlessly without extra boilerplate.
Modified Documents class:
@Data public class Documents { // Maps to the nested "snils.number" field in JSON @JsonProperty("snils.number") private String snilsNumber; // No annotation needed here—names match exactly private String somethingElse; }
How to deserialize:
ObjectMapper objectMapper = new ObjectMapper(); String json = "{ \"somethingElse\": \"foobar\", \"snils\": { \"number\": \"123\" } }"; Documents docs = objectMapper.readValue(json, Documents.class); // Access the values: System.out.println(docs.getSnilsNumber()); // Outputs "123" System.out.println(docs.getSomethingElse()); // Outputs "foobar"
Using Gson
If you prefer Gson instead, the approach is nearly identical—just use Gson's @SerializedName annotation with the same dot notation:
Modified Documents class:
@Data public class Documents { @SerializedName("snils.number") private String snilsNumber; private String somethingElse; }
Deserialization code:
Gson gson = new Gson(); String json = "{ \"somethingElse\": \"foobar\", \"snils\": { \"number\": \"123\" } }"; Documents docs = gson.fromJson(json, Documents.class);
Alternative: Custom Deserializer (if you need more control)
If you have complex logic or prefer not to use dot notation, you can create a custom deserializer. For Jackson, this would involve implementing JsonDeserializer<Documents> and registering it with the ObjectMapper, but this is overkill for your simple use case. The dot notation approach is far more concise.
Note on Dependencies
Make sure you have the relevant library added to your project:
- For Jackson: Include
com.fasterxml.jackson.core:jackson-databindin your Maven/Gradle build. - For Gson: Include
com.google.code.gson:gson.
内容的提问来源于stack exchange,提问作者faoxis

