如何避免封装对象的杰克逊JSON指针?

时间:2019-02-26 21:31:47

标签: java json jackson

我有一个封装第二个对象的对象。例如:

@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@fooId")
@Entity(name = "Foo")
@Table(name = "Foo")
@JsonIgnoreProperties(ignoreUnknown = true)
class Foo {
     @Column(name = "too")
     private String too;

     @Column(name = "baz")
     private String baz;

     @ManyToOne(cascade = CascadeType.REFRESH)
     @JoinColumn(name = "id", referencedColumnName = "id", insertable = false, updatable = false, foreignKey = @ForeignKey(name = "fk_bar")
     private Bar newBar;

     /// blahblah -- setters and getters and constructors
}

@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@newBarId")
@Entity(name = "Bar")
@Table(name = "Bar")
@JsonIgnoreProperties(ignoreUnknown = true)
class Bar {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long Id;  //database generated ID

    @Column(name = "barString")
    private String barString;  //string

     /// blahblah -- setters and getters and constructors
}

使用REST时,我将执行以下操作:

@RequestMapping(path="test/{id}", method = RequestMethod.GET, produces = "application/json")
public String getById(@PathVariable("id") Long id) throws Exception {
    List<Foo> myList = dao.findById(id);
    String rtn = objectMapper.writeValueAsString(myList);

    return rtn;
}

当我得到一个大列表时,每当有一个带有重复Bar的Foo时,它只会放下一个指针,这会在前端抛出Javascript。

有没有办法让Jackson停止为我提供封装对象的指针,并且每次都给我对象?

谢谢。

ETA:我在另一台计算机上,但是会出现类似以下的内容:

[
 {"@fooId" : 2, "too" : "basdf", "baz" : "asdf", "newBar" : { "@newBarId": 1, "id": 123, "barString" : "barString},
 {"@fooId": 3, "too" : "basafdsdf", "baz" : "asasdfdf", "newBar" : 1}
]

第二个newBar不再是对象,而是指向前一个的指针。希望这可以使事情变得更清楚。

我已经浏览了Hibernate和我的搜索结果-每次它们都与Bar对象一起返回。所以...这与ObjectMapper有关,但我不知道是什么。

0 个答案:

没有答案