将Entity对象转换为JSON [英] Convert Entity object to JSON

查看:537
本文介绍了将Entity对象转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将实体对象转换为json。我把

I need to convert entity object to json. I put

<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" />

到servlet配置文件,所以Spring可以自动将对象转换为json格式。但是春天不会这样做。我还将jackson jar添加到项目中。

to servlet configuration file, so Spring could convert object to json format autonatically. But Spring does not do it. I also added jackson jar to project.

控制器方法

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

GroupStudent

GroupStudent

@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]。

In browser I found that I have 406 error and error window error[object Object].

如果有人知道问题是什么,我会很乐意寻求帮助。

If anyone knows what the problem is, I will be gratfull for help.

谢谢。

推荐答案

如果您的对象加入了其他表,那么您只能在以下方式。

If your object joined other table then you can only do this in the following way.

首先,让我们注释与@JsonManagedReference,@ JsonBackReference的关系,让Jackson更好地处理这种关系:

First, let’s annotate the relationship with @JsonManagedReference, @JsonBackReference to allow Jackson to better handle the relation:

这是用户实体:

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是引用的后半部分 - 它将从序列化中省略。

@JsonManagedReference is the forward part of reference – the one that gets serialized normally. @JsonBackReference is the back part of reference – it will be omitted from serialization.

引自下面的链接。您可以访问更多。

Quoted from the link below. You can visit for more.

杰克逊 - 双向关系

这篇关于将Entity对象转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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