【问题标题】:Convert Entity object to JSON将实体对象转换为 JSON
【发布时间】:2017-08-15 23:05:06
【问题描述】:

我需要将实体对象转换为 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 并没有这样做。我还在项目中添加了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]。

如果有人知道问题出在哪里,我将不胜感激。

谢谢。

【问题讨论】:

  • 406 是不可接受的。您如何尝试访问您的控制器 url?
  • 如果你是关于 Ajax 函数:function addGroupAjax() { var groupStudentNumber = $('#groupStudentNumber').val(); $.ajax({ type: "POST", url: "/IRSystem/addData.html", contentType: "application/json; charset=utf-8", dataType: "json", data: "{\"groupStudentNumber\ ":\"IS-02\"}", 成功: 函数(响应) { }, 错误: 函数(e) { alert("Error" + e); } }); }
  • 好的。 GroupStudent 里面有什么?请给我看。我忘了提到你的类路径中必须有 jackson 库。
  • 我添加了更高级别的 GroupStudent 课程。我把杰克逊库放到类路径中

标签: java json spring


【解决方案1】:

如果您的对象加入了其他表,那么您只能通过以下方式执行此操作。

首先,让我们用@JsonManagedReference、@JsonBackReference 来注释关系,让Jackson 更好地处理关系:

这是“用户”实体:

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

引用自以下链接。您可以访问以了解更多信息。

Jackson – Bidirectional Relationships

【讨论】:

  • 是的。我需要这个new ObjectMapper().writeValueAsString(item);谢谢
【解决方案2】:

@RequestMapping(produces="application/json") 是您需要的,不要忘记在您的 JS 代码中发出 POST 请求(不是 GET)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 2017-01-03
    相关资源
    最近更新 更多