gpt4 book ai didi

java - 搜索将对象之间的双向链接转换为 JSON 格式的正确方法

转载 作者:太空宇宙 更新时间:2023-11-04 09:50:16 25 4
gpt4 key购买 nike

我一直在寻找正确的方法来转换我的 Student对象(带有嵌套的 Marks 对象)到 JSON格式。

我尝试将获取类型组合为 LAZYEAGER ,但这无济于事。获取StackOverflowException .

过了一段时间,我找到了一个解决方案 -> 使用注释 @JsonIgnore嵌套Marks对象,然后输入 StudentsMarks反对 JSON单独字符串作为下一个:

String jsonStringStud = new ObjectMapper().writeValueAsString(student);
String jsonStringMarks = new ObjectMapper().writeValueAsString(student.getCtlgMarks());

之后我必须添加 Marks Students里面,但我怀疑这是不好的做法。

这是我的期望:

String jsonStringStud = new ObjectMapper().writeValueAsString(student);

预期输出:Students{studentId=1, StudentName=Alex, ctlgMarks=Marks{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 + '}';
}
}

这是我用来获取 Student 的方法通过 id 获取对象并将其转换为 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;
}

最佳答案

您应该使用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"
}

关于java - 搜索将对象之间的双向链接转换为 JSON 格式的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54853178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com