복붙노트

[SPRING] Entity 객체를 JSON으로 변환

SPRING

Entity 객체를 JSON으로 변환

엔티티 객체를 json으로 변환해야합니다. 나는 넣는다.

<bean class = "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <array>
            <bean class = "org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <property name="supportedMediaTypes" value="application/json" />
                <property name="objectMapper">
                    <ref bean="JacksonObjectMapper" />
                </property>
            </bean>
        </array>
    </property>
</bean>

<bean id="JacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />

서블릿 설정 파일에 추가하면 Spring은 객체를 자동으로 json 형식으로 변환 할 수있다. 그러나 봄은 그것을하지 않습니다. 프로젝트에 jackson jar도 추가했습니다.

제어기 방법

@RequestMapping(value = "/addData.html", method = RequestMethod.POST)
public @ResponseBody GroupStudent addNewGroup(@RequestBody GroupStudent group) {
    return group;    
}

그룹 스터디

@Entity
@Table(name = "GroupStudent")
@NamedQueries({ 
@NamedQuery(name = "GroupStudent.getAllGroups", // get all groups
            query = "select g from GroupStudent g"),
@NamedQuery(name = "GroupStudent.getGroupByName", // get group by name
            query = "select g from GroupStudent g where g.groupStudentNumber = :name")
})
public class GroupStudent implements Serializable {
public GroupStudent() {}

public GroupStudent(String groupStudentNumber) {
    this.groupStudentNumber = groupStudentNumber;
}

// create connectivity with table Student
private Set<Student> students = new HashSet<Student>();

@OneToMany(mappedBy = "groupStudent", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<Student> getStudents() {
    return this.students;
}   

public void setStudents(Set<Student> students) {
    this.students = students;
}   

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "group_id_seq")
@SequenceGenerator(name = "group_id_seq", sequenceName = "GroupStudent_seq", allocationSize = 1)
@Column(name = "GroupStudentId")
public Long getGroupStudentId() {
    return this.groupStudentId;
}

public void setGroupStudentId(Long groupStudentId) {
    this.groupStudentId = groupStudentId;
}

@Column(name = "GroupStudentNumber")
public String getGroupStudentNumber() {
    return this.groupStudentNumber;
}

public void setGroupStudentNumber(String groupStudentNumber) {
    this.groupStudentNumber = groupStudentNumber;
}

// table GroupStudent fields
private Long groupStudentId;
private String groupStudentNumber;

}

브라우저에서 406 오류 및 오류 창 오류 [object Object]가 있음을 발견했습니다.

문제가 무엇인지 아는 사람이라면 도움에 감사 할 것입니다.

고맙습니다.

해결법

  1. ==============================

    1.@RequestMapping (produce = "application / json")은 필요한 것이므로 JS 코드에서 GET이 아닌 POST 요청을하는 것을 잊지 마십시오.

    @RequestMapping (produce = "application / json")은 필요한 것이므로 JS 코드에서 GET이 아닌 POST 요청을하는 것을 잊지 마십시오.

  2. ==============================

    2.당신의 객체가 다른 테이블에 합류했다면 다음과 같은 방법으로 만이 작업을 수행 할 수 있습니다.

    당신의 객체가 다른 테이블에 합류했다면 다음과 같은 방법으로 만이 작업을 수행 할 수 있습니다.

    먼저, @JsonManagedReference, @JsonBackReference와의 관계에 주석을 달아 잭슨이 관계를보다 잘 처리 할 수있게하십시오.

    "사용자"엔티티는 다음과 같습니다.

    public class User {
        public int id;
        public String name;
    
        @JsonBackReference
        public List<Item> userItems;
    }
    

    그리고 "아이템":

    public class Item {
        public int id;
        public String itemName;
    
        @JsonManagedReference
        public User owner;
    }
    

    이제 새 항목을 테스트 해 봅시다.

    @Test
    public void
      givenBidirectionRelation_whenUsingJacksonReferenceAnnotation_thenCorrect()
      throws JsonProcessingException {
    
        User user = new User(1, "John");
        Item item = new Item(2, "book", user);
        user.addItem(item);
    
        String result = new ObjectMapper().writeValueAsString(item);
    
        assertThat(result, containsString("book"));
        assertThat(result, containsString("John"));
        assertThat(result, not(containsString("userItems")));
    }
    

    다음은 직렬화의 출력입니다.

    {
     "id":2,
     "itemName":"book",
     "owner":
        {
            "id":1,
            "name":"John"
        }
    }
    

    참고 사항 :

    @JsonManagedReference는 참조의 앞으로의 부분입니다 - 정상적으로 직렬화됩니다. @JsonBackReference는 참조의 뒷부분입니다. 직렬화에서 생략됩니다.

    아래 링크의 인용문. 더 많은 것을 위해 방문 할 수 있습니다.

    잭슨 - 양방향 관계

  3. from https://stackoverflow.com/questions/19928151/convert-entity-object-to-json by cc-by-sa and MIT license