当前位置: 首页 > 知识库问答 >
问题:

将Entity对象转换为JSON

饶德元
2023-03-14

我需要将实体对象转换为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" />

到 servlet 配置文件,因此 Spring 可以自动将对象转换为 json 格式。但Spring没有这样做。我还在项目中添加了杰克逊罐子。

控制器方法

@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 错误和错误窗口错误[对象对象]。

如果有人知道问题出在哪里,我会很高兴得到帮助。

谢谢。

共有2个答案

宋新知
2023-03-14

@请求映射(产生="应用程序/json")是您需要的,不要忘记在您的JS代码中发出POST请求(不是GET)。

侯兴为
2023-03-14

如果你的对象连接了其他的表,那么你只能用下面的方法。

首先,让我们注释一下与@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"
    }
}

请注意:

@JsonManaged引用是引用的前部分——正常序列化的部分。@JsonBack引用是引用的后部分——它将从序列化中省略。

引自以下链接。您可以访问以获取更多信息。

Jackson–双向关系

 类似资料:
  • 首先,我是SpringWebFlux的新手,正在尝试建立一个反应式spring启动项目的POC。我有一个用例,需要将检索到的实体类(PartyDTO)转换为Mono对象(Person:这是一个没有构造函数的第三方业务对象,我无法修改它)。我在谷歌上搜索,但找不到与我的用例相匹配的答案。 第三方对象: 我的课程如下: 调用我的存储库的服务类。 如上图所示,我尝试将平面图与我的自定义映射器一起使用,但

  • 问题内容: 我有一个JSON对象,我将其转换为并在此处进行一些处理。稍后,我想转换相同的缓冲区数据以转换为有效的JSON对象。 我正在研究Node V6.9.1 下面是我尝试过的代码,但是当我转换回JSON却无法打开该对象时遇到了。 所以我尝试使用检查方式打印整个对象 如果我尝试像数组一样读取它 我也尝试解析它抛出 我需要将其视为我创建的真实对象(我的意思是像上面声明的那样)。 请帮忙.. 问题答

  • 我正试图将下面的json转换成java bean,需要你的帮助 Sort.json 我的豆子看起来像 我的测试课是 我看到的错误是 请建议:

  • 例如:Date值为:“dateCollected”:fri Jul 07 00:00:00 IST 1989, 但它只服用星期五而不是整个日期。

  • 问题内容: 我正在将struts2用于Action,将jquery用于UI … 我想知道如何将Map对象转换为JSON对象并将其发送回UI, 现在可以在JSP页面中将其打印为普通的Java Map对象: 但我希望它是这样的: 我将如何实现这一目标…? 问题答案: 尝试Gson: 不过,我不建议将这种代码放入JSP。诸如此类的事情应该存在于Servlet或Action类之类的控制器中。 您还绝对不希

  • 问题内容: 我对服务进行了调用,并将响应存储在中。但是,我试图将其转换为类对象并得到错误。这是我的代码: 响应如下所示: 这是该类的样子: 但是我得到了错误: 我究竟做错了什么? 编辑1: 这是从答案中使用gson的尝试: 但是我得到了错误: 问题答案: 找出问题所在。需要提取jsonobject而不是获取字符串。这是解决此问题的行: