【问题标题】:@JsonProperty annotation is getting ignored in mongodb collection@JsonProperty 注释在 mongodb 集合中被忽略
【发布时间】:2021-12-05 21:16:40
【问题描述】:

由于我是 springbootmongodb 的新手,所以我使用了 https://start.spring.io/ 并生成了一个具有以下设置的演示项目。

然后创建如下模型:

package com.example.model;

import java.io.Serializable;
import java.time.LocalDate;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.mongodb.core.mapping.Document;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
@Configuration

@Document(collection = "customer")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Customer implements Serializable {
    
    private static final long serialVersionUID = 6748432793461621268L;

    @JsonProperty("customer_id")
    private String customerId;
    
    @JsonProperty(value= "external_customer_reference_id")
    private String externalCustomerReferenceId;
    
    
    @JsonProperty("title")
    private String title;

    @JsonProperty("first_name")
    private String firstName;
    
    @JsonProperty("middle_name")
    private String middleName;

    @JsonProperty("last_name")
    private String lastName;
    
    @JsonProperty("email")
    private String email;

    @JsonProperty("phone")
    private String phone;

    @JsonProperty("note")
    private String note;
    
    @JsonProperty("date_of_birth")
    private String dateOfBirth;

    @JsonProperty("sex")
    private String sex;
    
    @JsonProperty("contact_address")
    private Address address;
    
    @CreatedDate
    @JsonProperty("create_timestamp")
    private LocalDate createdDate;
    
    @LastModifiedDate
    @JsonProperty("modified_timestamp")
    private LocalDate modifiedDate;
    
    
}

我可以将客户保存在mongodb 集合customer 中。但集合属性名称与@JsonProperty("modified_timestamp")不同。

为什么db集合属性名和JsonProperty不一样?如何获取与JsonProperty 相同的数据库集合属性名称?

【问题讨论】:

    标签: mongodb spring-boot jackson lombok


    【解决方案1】:

    在 MongoDB 中,您正在使用其属性名称保存一个对象。 JsonProperty 注解映射反序列化和给定对象的序列化。

    可用于将非静态方法定义为 逻辑属性的“setter”或“getter”(取决于它的 签名),或要使用的非静态对象字段(序列化, 反序列化)作为逻辑属性。默认值 ("") 表示 字段名称用作属性名称,无需任何修改, 但可以指定为非空值以指定不同的名称。 属性名是指外部使用的名称,如中的字段名 JSON 对象。

    https://fasterxml.github.io/jackson-annotations/javadoc/2.8/com/fasterxml/jackson/annotation/JsonProperty.html

    通过使用@Field 属性注释,您可以将属性保存为与对象不同的名称。

    【讨论】:

    • 感谢您的回答。那么,如何保存属性名称与 JsonProperty 相同的对象?
    • 我已经更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 2012-09-09
    • 2019-10-16
    • 2018-01-23
    • 2012-05-19
    • 2015-01-09
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多