我尝试了很多方法,并详细发布了我的问题。
这是我的家长班
@Entity
@Table(name = "Project")
//@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id")
public class Project implements Serializable{
@Expose
int id;
@Expose
String projectName;
@Expose
String userID;
// Date dateCreated;
@Expose
String dateCreated;
@Expose
String status;
@Expose
String houseType;
@Expose
private List<UnitDetails> unitDetails = new ArrayList<>();
@Expose
private List<RoomDetails> roomDetails = new ArrayList<>();
@GeneratedValue
@Column(name = "id")
public int getId() {
return id;
}
@OneToMany( mappedBy="unitDetails", fetch = FetchType.LAZY)
public List<UnitDetails> getUnitDetails() {
return unitDetails;
}
public void setUnitDetails(List<UnitDetails> unitDetails) {
this.unitDetails = unitDetails;
}
@OneToMany(mappedBy="roomDetails", fetch = FetchType.LAZY)
public List<RoomDetails> getRoomDetails() {
return roomDetails;
}
public void setRoomDetails(List<RoomDetails> roomDetails) {
this.roomDetails = roomDetails;
}
这是我的儿童课程
@Entity
@Table(name="Unit_Details")
//@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id")
public class UnitDetails {
@Expose
int unitDetailsID;
@Expose
int designID;
@Expose
String unit;
@Expose
double length;
@Expose
double breadth;
@Expose
double height;
@Expose
String img;
@Expose
String type;
@Expose
String color;
@JsonIgnore
private Project unitDeTails;
@Id
@GeneratedValue
@Column(name="unitDetailsID", unique=true, nullable=false)
public int getUnitDetailsID() {
return unitDetailsID;
}
@ManyToOne
@JoinColumn(name="id", insertable=true, updatable=false)
public Project getUnitDetails() {
return unitDeTails;
}
public void setUnitDetails(Project unitDetails) {
this.unitDeTails = unitDetails;
}
这是我的控制器
public class ProjectController extends ActionSupport implements
ModelDriven<Object> {
public HttpHeaders index() {
model = objProjectDAOImpl.getProjectDetails(userID);
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
System.out.println(gson.toJson(model));
model = gson.toJson(model);
return new DefaultHttpHeaders("index").disableCaching();
}
我能够正确地保存细节,没有任何循环错误。当我尝试检索时,我收到了循环引用错误。然后我使用Gson只暴露所需的字段,现在我得到下面的错误
HTTP Status 500 - A JSONObject text must begin with '{' at character 1 of
我知道这不是JSON格式,但我认为GSON会处理这个问题,或者让我知道我必须使用不同的方法来修复这个
它显示的结果如下所示,看起来像一个数组[{"id":139,"projectName":"ABCD","unitDetails":[{"unitDetailsID":575,…
这可能不是正确的修复方法,但我不得不接受它。
在我设置了父类之后,我确保子类没有对父类的任何引用,也没有持有任何引用父类的对象,基本上将子引用设置为null,这样它就不会循环。它对我有效
为什么不使用@JsonIdentityInfo
注释?我几个月前也遇到过同样的问题,使用
@JsonIdentityInfo(property = "id", generator = ObjectIdGenerators.PropertyGenerator.class, scope = YourEntity.class)
成功了。属性id
对应于YourEntity中的getId()。@JsonIdentityInfo
注释来自Jackson库,而不是Gson。或者,您可以使用同一库中的@JsonManagedReference
和/或@JsonBackReference
。