搜索将对象之间的双向链接转换为JSON格式的正确方法 [英] Searching proper way to convert my two-way linkage between objects to JSON format

查看:30
本文介绍了搜索将对象之间的双向链接转换为JSON格式的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I stuck searching proper way to convert my Student object (with nested Marks object) to JSON format.

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

I tried to combine fetch type as LAZY and EAGER, but it couldn't help. Getting StackOverflowException.

一段时间后,我找到了一个解决方案->在嵌套的Marks对象中使用注释@JsonIgnore,然后将StudentsMarks对象分别放入JSON字符串中,如下所示:

After some time I found one solution -> to use annotation @JsonIgnore in nested Marks object, and put Students and Marks objects to JSON string separately as next :

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

此后,我不得不在Students内添加Marks,但是我怀疑这是不好的做法.

After that I had to add Marks inside of Students, but I suspect that this is bad practice.

这是我期望的:

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

预期输出:学生{studentId = 1,studentName = Alex,ctlgMarks =标记{marksId = 1,markValue = Bad}}

Expected output: Students{studentId=1, studentName=Alex, ctlgMarks=Marks{marksId=1, markValue=Bad}}

您能否看一下我的代码,并让我知道是否存在将对象转换为JSON格式的正确方法?

Could you please look at my code, and let me know if there is proper way to convert my object to JSON format?

如果您编写类似"代码或之前/之后的代码,这将非常有帮助.

It would be very helpful, if you write "something like" code or before/after code.

这是我的代码:

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的方法.

Here is method I use to get Student object by id and convert it to 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格式字符串

//Separately get json format string for student and marks

            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注释,以显示其工作原理.型号:

You should use JsonBackReference annotation. I have simplified your code only to Jackson annotation to show how it works. Model:

@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:

Above code prints. Student 1:

{
  "studentId" : 1,
  "studentName" : "Rick",
  "ctlgMarks" : {
    "marksId" : 1,
    "markValue" : "Value"
  }
}

学生2:

{
  "studentId" : 2,
  "studentName" : "Morty",
  "ctlgMarks" : {
    "marksId" : 1,
    "markValue" : "Value"
  }
}

标记:

{
  "marksId" : 1,
  "markValue" : "Value"
}

这篇关于搜索将对象之间的双向链接转换为JSON格式的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆