【问题标题】:How to use Jackson annotations( or any other way)to get a complex data in the deserialization?如何使用 Jackson 注释(或任何其他方式)在反序列化中获取复杂数据?
【发布时间】:2017-02-27 02:28:24
【问题描述】:

我使用带有 json 序列化/反序列化的实体模型来存储/检索数据。 我面临反序列化延迟加载数据的问题。

也就是说,我已经这样定义了我的实体、超类、接口;

ATG 类

@Entity
@Table(name = "atg", uniqueConstraints = @UniqueConstraint(columnNames = "code"))
public class ATG extends ParentEntity {

    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "companyid")
    Manufacturer manufacturer;

    getManufacturer();
    setManufacturer();    
}

客户类

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Customer implements HasCustomer {

    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    @ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
    @JoinColumn(name = "customer2_id", nullable = true)
    private Customer customer;

    getCustomer();
    setCustomer();
}

父实体

@MappedSuperclass
public abstract class ParentEntity implements  HasCustomer{

    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    @ManyToOne( fetch = FetchType.LAZY)
    @JoinColumn(name = "customer2_id", nullable = false)
    private Customer customer;

    getCustomer();
    setCustomer();
}

HasCustomer 界面

public interface HasCustomer extends Serializable{

    public Customer getCustomer();

    public void setCustomer(final Customer customer);

    public Long getCustomerId();

    public void setCustomerId(final Long customerId);
}

客户类有对客户对象的引用(逻辑要求)。

我对我的服务端点进行 REST 调用以从数据库中检索数据。 Ide 将那些复杂的数据类型定义为 fetch = FetchType.LAZY。 当用户真的需要那些带有响应的数据时,他会指定。因此,在后端,我们通过设置 FetchMode.JOIN 来获取数据。 (这行得通)。

唯一的问题是,Json 注释。在这种情况下我应该如何指定注释? 如果我将 jsonIgnore 保持在一个级别,它可能会阻止结果,或者在不要求用户获取复杂数据时我一直看到结果

我在所有 getter、setter 和变量定义中尝试了 @jsonIgnore /@jsonproperty 注释。 (我相信我尝试了所有组合:)

但是没有一个返回期望的结果。

我想保留适当的注释以在调用 ATG 服务时检索客户数据和制造商数据

谁能帮帮我?

我使用 jackson(com.fasterxml.jackson) V 2.6.3 hibernate v 5.2.1.Final。

【问题讨论】:

  • 什么是“期望的结果”?这不是 100% 明显的,因此您可能希望将其指定为 JSON 或解释为“不应具有属性‘客户’”。

标签: java json hibernate orm jackson


【解决方案1】:

我不确定您是否应该像这样使用 Jackson,但这可能会有所帮助。

定义客户序列化程序

public class CustomerSerializer extends JsonDeserializer<Customer> {

   public Customer deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        ....
    }
}

然后在你的界面中使用它

@JsonDeserialize(using = CustomerSerializer.class)
public class Customer implements HasCustomer {

【讨论】:

  • 这个解决方案每次都给'客户'。看起来我的 customJsondeserilizer 类根本没有被调用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-24
  • 2015-02-26
  • 1970-01-01
  • 2018-04-04
  • 1970-01-01
  • 1970-01-01
  • 2013-09-10
相关资源
最近更新 更多