简体   繁体   中英

Convert Entity object to 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" />

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.

Controller method

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

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;

}

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.

Thank you.

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

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

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

Here's the “User” entity:

public class User {
    public int id;
    public String name;

    @JsonBackReference
    public List<Item> userItems;
}

And the “Item“:

public class Item {
    public int id;
    public String itemName;

    @JsonManagedReference
    public User owner;
}

Let's now test out the new entities:

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

Here is the output of serialization:

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

Note that:

@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.

Jackson – Bidirectional Relationships

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM