Json使用Jackson使用JaxB注释进行映射

时间:2014-04-08 06:36:38

标签: java json web-services jaxb jackson

如何使用Jackson序列化此类

package com.progressivebeef.service.response;

@XmlRootElement(name = "response")
@XmlSeeAlso({ User.class,             Profile.class,MenuItem.class,Feedlot.class,Document.class,FeedlotDocument.class })
public final class PBResponse {

private Integer status = FAILURE;
private String code;
private String message;
private Integer totalRecords;
private List<Model> list = new ArrayList<Model>();


public Integer getStatus() {
    return status;
}

public void setStatus(Integer status) {
    this.status = status;
}

@XmlElementWrapper(name = "PBBeans")
@XmlAnyElement
public List<Model> getList() {
    return list;
}

public void setList(List<Model> list) {
    this.list = list;
}

public String getCode() {
    return code;
}

public void setCode(String code) {
    this.code = code;
}

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}

public Integer getTotalRecords() {
    return totalRecords;
}

public void setTotalRecords(Integer totalRecords) {
    this.totalRecords = totalRecords;
}

/**
 * @author tiqbal
 * Resets the response.
 */
public void reset(){

    this.status = FAILURE;
    this.list = new ArrayList<Model>();
    this.code = null;
    this.message = null;
    this.totalRecords = null;
}
}

杰克逊没有拿起@XmlElementWrapper @XmlSeeAlso注释,杰克逊也没有映射@XmlRootElement注释。我正在使用Jackson 1.9.0。杰克逊在列表中放置了元素,但没有映射POJO类的根元素。

这是示例方法。

package com.progressivebeef.service.impl;

@Service("/ActivityServiceImpl/")
@Path("/activityservice/")
public class ActivityServiceImpl implements ActivityService {

@POST
@Produces(MediaType.APPLICATION_JSON)
@Override
public Response inputJson(User user ) {

    System.out.println("user ");


    user.setUser_name("check user name");

    Profile profile = new Profile();

    profile.setFirst_name("abc");
    profile.setLast_name("khan");

    user.setProfile( profile );

    PBResponse response = new PBResponse();
    response.getList().add(user);

    return Response.ok(response).build();
}
}

它生成的响应是“{”响应“:{”status“:0,”PBBeans“:[{”user_name“:”检查用户名“,”密码“:”click123“,”user_role_key“:2 , “简档”:{ “first_name的”: “ABC”, “姓氏”: “汗”, “表名”: “pb_profile”, “PK”: “PROFILE_ID”}, “表名”: “pb_user”, “PK” : “USER_ID”}]}}“

没有在PBBeans标记内获取bean的根名称。

1 个答案:

答案 0 :(得分:0)

希望this有所帮助。基本上,您需要在映射器中将WRAP_ROOT_VALUE设置为true。