【问题标题】:Spring Jackson deserialization only picks the first item of an arraySpring Jackson 反序列化只选择数组的第一项
【发布时间】:2018-05-29 12:27:06
【问题描述】:

我用 spring boot 构建了一个 api rest。我有一个父子关系,把孩子当作一个对象数组。

问题是反序列化只选择数组的第一项。其他一切似乎都很好。父母和孩子也在数据库中。

我发送这样的东西:

"user": {
  "name": "foo",
  "childs": [
    {
       "name": "bar",
        ....
    },
    {
       "name": "foobar",
        ....
    }
  ],
  ....
}

但得到了坚持:

"user": {
  "id": 1,
  "name": "foo",
  "childs": [
    {
        "id": 1,
        "name": "bar",
        ....
    }
  ],
  ....
}

这有什么线索吗?

更新

父实体:

@JsonIdentityInfo(
        generator = ObjectIdGenerators.PropertyGenerator.class, 
        property = "id",
        scope = User.class)
@Entity( name = "users" )
@Table( name = "users" )
public class User extends ModelEntity {
    
    Model's fields...
    ...

    @JsonView( value = {DTOViews.PrivateProfile.class, DTOViews.Owner.class} )
    @JsonManagedReference( value = "User-ProfessionalExperience" )
    @OneToMany( mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY )
    private Set<ProfessionalExperience> professionalExperiences;
}

子实体:

@JsonIdentityInfo(
    generator = ObjectIdGenerators.PropertyGenerator.class, 
    property = "id",
    scope = ProfessionalExperience.class)
@Entity
@Table( name = "professional_experiences")
public class ProfessionalExperience extends ModelEntity {

    Model's fields...
    ...

    @JsonBackReference( value = "User-ProfessionalExperience" )
    @ManyToOne
    @JoinColumn(name = "user_id", nullable = false)
    private User user;
}

控制器:

@RequestMapping(method = RequestMethod.POST)
public MappingJacksonValue create(@RequestBody @Valid User userToCreate, BindingResult result) {

    ...
}

提前谢谢大家。

【问题讨论】:

  • 你能给出这个过程的一些实际代码吗?
  • 我要查看user的类,child的类
  • @craigwor 我更新了代码。谢谢你们。

标签: java arrays spring spring-boot jackson


【解决方案1】:

所以,我终于解决了。问题来自关系集合类型和 hasCode() / equals() 方法。

我的模型中的所有实体都从“ModelEntity”类扩展而来。此类为所有扩展模型提供 id 和记录活动字段以及基于这些字段的 hasCode/equals 方法。由于“User”和“ProfessionalExperience”之间的关系被定义为一个集合,它不能存储重复的元素。

所以,为了告诉 jackson 子元素是不同的元素,我们需要用每个模型类中定义的字段来覆盖每个模型类中的 hasCode/equals。

【讨论】:

    猜你喜欢
    • 2018-07-20
    • 2017-08-25
    • 2013-08-22
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    • 2020-07-27
    • 2021-06-22
    • 2012-10-22
    相关资源
    最近更新 更多