Searching proper way to convert my two-way linkage between objects to JSON format

后端 未结 1 544
感情败类
感情败类 2021-01-24 16:44

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

I tried to combine fetch type

相关标签:
1条回答
  • 2021-01-24 17:33

    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
    }
    

    Example usage:

    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));
        }
    }
    

    Above code prints. Student 1:

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

    Student 2:

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

    Marks:

    {
      "marksId" : 1,
      "markValue" : "Value"
    }
    
    0 讨论(0)
提交回复
热议问题