You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Jackson从嵌套JSON对象映射字段至Java实体类?

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-databind in your Maven/Gradle build.
  • For Gson: Include com.google.code.gson:gson.

内容的提问来源于stack exchange,提问作者faoxis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:46:18