我一直在寻找将Student
对象(带有嵌套的Marks
对象)转换为JSON
格式的正确方法。
我尝试将提取类型组合为LAZY
和EAGER
,但这无济于事。得到StackOverflowException
。
一段时间后,我找到了一个解决方法->在嵌套的@JsonIgnore
对象中使用注释Marks
,并将Students
和Marks
对象放入JSON
字符串中分别作为下一个:
String jsonStringStud = new ObjectMapper().writeValueAsString(student);
String jsonStringMarks = new ObjectMapper().writeValueAsString(student.getCtlgMarks());
此后,我不得不在Marks
内添加Students
,但是我怀疑这是不好的做法。
这是我期望的:
String jsonStringStud = new ObjectMapper().writeValueAsString(student);
预期输出:学生{studentId = 1,studentName = Alex,ctlgMarks =标记{marksId = 1,markValue = Bad}}
能否请您查看我的代码,并让我知道是否存在将对象转换为JSON
格式的正确方法?
如果您编写“类似”代码或之前/之后的代码,这将非常有帮助。
这是我的代码:
表Student
CREATE TABLE "student" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
"name" NVARCHAR NOT NULL UNIQUE,
"marks_fk" INTEGER NOT NULL,
FOREIGN KEY("marks_fk") REFERENCES "ctlg_marks"("id")
);
表Marks
CREATE TABLE "ctlg_marks" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
"mark_value" NVARCHAR NOT NULL UNIQUE
);
实体Students
package entities;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@Entity
@Table(name = "student")
@JsonPropertyOrder({"id","name","ctlgMarks"})
public class Students implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int studentId;
@Column(name = "name")
private String studentName;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "marks_fk")
@JsonIgnore
private Marks ctlgMarks = new Marks();
public Students() {
}
@Override
public String toString() {
return "Students{" + "studentId=" + studentId +
", studentName=" + studentName +
", ctlgMarks=" + ctlgMarks + '}';
}
}
实体Marks
package entities;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.Cascade;
@Getter
@Setter
@AllArgsConstructor
@Entity
@Table(name = "ctlg_marks")
public class Marks implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int marksId;
@Column(name = "mark_value")
private String markValue;
@Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
@OneToMany(mappedBy = "ctlgMarks", fetch = FetchType.LAZY)
private Set<Students> students = new HashSet<>();
public Marks() {
}
@Override
public String toString() {
return "Marks{" + "marksId=" + marksId +
", markValue=" + markValue + '}';
}
}
这是我用来通过ID获取Student
对象并将其转换为JSON
的方法。
public String readWithinSession(int id) {
Students student = new Students();
String str = "";
SessionFactory factory1 = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Students.class)
.buildSessionFactory();
Session session = factory1.getCurrentSession();
try {
session.beginTransaction();
student = session.get(Students.class, id);
if (student != null) {
Hibernate.initialize(student.getCtlgMarks());
System.out.println("INITIALIZE USED");
}
//分别获取学生和成绩的json格式字符串
try {
String jsonStringStud = new ObjectMapper().writeValueAsString(student);
String jsonStringMarks = new ObjectMapper().writeValueAsString(student.getCtlgMarks());
/*
After getting json student string: {"studentId":1,"studentName":"Alex"}
After getting json marks string: {"marksId":1,"markValue":"Bad","students":[{"studentId":1,"studentName":"Alex"}]}
*/
//Separately get objects student and marks
try {
Students studObj = new ObjectMapper().readValue(jsonStringStud, Students.class);
Marks marksObj = new ObjectMapper().readValue(jsonStringMarks, Marks.class);
System.out.println("After got stud obj from string: " + studObj);
System.out.println("After got marks obj from string: " + marksObj);
/*
After getting stud obj from json string: Students{studentId=1, studentName=Alex, ctlgMarks=Marks{marksId=0, markValue=null}}
After getting marks obj from json string: Marks{marksId=1, markValue=Bad}
*/
//Join marks to student
studObj.setCtlgMarks(marksObj);
System.out.println("Student after got marks object" + studObj);
/*
Student after got marks objectStudents{studentId=1, studentName=Alex, ctlgMarks=Marks{marksId=1, markValue=Bad}}
*/
} catch (IOException ex) {
Logger.getLogger(StudentsDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (JsonProcessingException ex) {
Logger.getLogger(Domain.class.getName()).log(Level.SEVERE, null, ex);
}
session.getTransaction().commit();
} finally {
factory1.close();
}
return str;
}
答案 0 :(得分:0)
您应该使用JsonBackReference
注释。我仅将您的代码简化为Jackson
注释,以显示其工作原理。型号:
@JsonPropertyOrder({"studentId", "studentName", "ctlgMarks"})
class Students {
private int studentId;
private String studentName;
private Marks ctlgMarks;
// getters, setters, constructors
}
class Marks {
private int marksId;
private String markValue;
@JsonBackReference
private Set<Students> students;
// getters, setters, constructors
}
用法示例:
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class JsonApp {
public static void main(String[] args) throws Exception {
Marks marks = new Marks();
Students student0 = new Students(1, "Rick", marks);
Students student1 = new Students(2, "Morty", marks);
marks.setMarksId(1);
marks.setMarkValue("Value");
marks.setStudents(new HashSet<>(Arrays.asList(student0, student1)));
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
System.out.println(mapper.writeValueAsString(student0));
System.out.println(mapper.writeValueAsString(student1));
System.out.println(mapper.writeValueAsString(marks));
}
}
以上代码打印。学生1:
{
"studentId" : 1,
"studentName" : "Rick",
"ctlgMarks" : {
"marksId" : 1,
"markValue" : "Value"
}
}
学生2:
{
"studentId" : 2,
"studentName" : "Morty",
"ctlgMarks" : {
"marksId" : 1,
"markValue" : "Value"
}
}
标记:
{
"marksId" : 1,
"markValue" : "Value"
}