ObjectMapper 的默认行为

Default behaviour of ObjectMapper

我有一个 class 对象,我正在使用 jackson ObjectMapper 将其转换为 json。 转换后,它会为每个变量生成两个条目。这种行为是否正常?如果正常,有人可以向我解释一下吗?

我目前的理解是对象映射器使用 @JsonProperty 注释来创建字段名称

@Data
@Entity
@Table(name = "oracle_blob")
public class OracleBlob {

    @Id
    @GenericGenerator(name = "native", strategy = "native")
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
    @Column(name ="id")
    @JsonIgnore
    private Long id;

    @Column(name ="source_entity")
    @JsonProperty("Source_Entity")
    private String Source_Entity;

    @Column(name ="interface_name")
    @JsonProperty("Interface_Name")
    private String Interface_Name;

    @Column(name ="batch_id")
    @JsonProperty("Batch_Id")
    private String Batch_Id;

    @Column(name ="message")
    @JsonProperty("Message_Content")
    private String Message_Content;

}

输出

{
   "source_Entity":"test source2",
   "interface_Name":"test Interface Name2",
   "batch_Id":"testbatchId2",
   "message_Content":"test message2",
   "Source_Entity":"test source2",
   "Interface_Name":"test Interface Name2",
   "Batch_Id":"testbatchId2",
   "Message_Content":"test message2"
}

字段名称不要使用大写字母,因为 Jackson 将解析 getter(在您的示例中由 lombok 生成)并根据 getInterface_Name() + 一个字段搜索 interface_name @JsonProperty("Interface_Name"),等

Jackson 2.5 did add MapperFeature.USE_STD_BEAN_NAMING, enabling of which gets handling you want. It is disabled by default for backwards-compatibility reasons. Another alternative (and only choice if you are using an earlier version) would be to annotate getter with @JsonProperty as well; if so, field and getter would be properly coupled.

在此处查看完整答案:https://github.com/FasterXML/jackson-databind/issues/729#issuecomment-84761480