且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

直接自引用导致循环超类问题JSON

更新时间:2023-01-17 17:18:47

通常在响应中排除属性就像添加 @JsonIgnore $ c $一样简单c>对其getter的注释,但如果您不想将此注释添加到父类,则可以覆盖getter,然后在其上添加注释:

Usually excluding attributes in a response is as easy as adding a @JsonIgnore annotation to their getters, but if you don't want to add this annotation to a parent class, you could override the getter and then add the annotation on it:

public class Special extends BaseEntity implements Serializable {
    ...
    @JsonIgnore
    public ApplicationInstance getAppInstance() {
        return this.appInstance;
    }
    ...
}

注意:由于有多个框架,请确保使用正确的 @JsonIgnore 注释,否则将被忽略,请参阅这个答案例如。

NOTE: As there are several frameworks, make sure that you are using the correct @JsonIgnore annotation or it will be ignored, see this answer for instance.

另一种选择,更手动,只是为了创建一个bean响应将是特殊实例的子集:

Another option, more "manual", is just creating a bean for the response which would be a subset of the Special instance:

@GET
@Path("{ref}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(value = MediaType.TEXT_PLAIN)
public SpecialDTO findByGuestRef(@PathParam("ref") String pRefeference) {
  // find the special and return it
 return new SpecialDTO(special);
}


public class SpecialDTO {

    //declare here only the attributes that you want in your response

    public SpecialDTO(Special sp) {
        this.attr=sp.attr; // populate the needed attributes
    }

}