将没有根元素的JSON响应映射到POJO JAXB绑定?

时间:2018-03-22 18:47:47

标签: json xml-parsing jaxb apache-camel pojo

如何使用JAXB注释将JSON(无根元素)映射到XML? 似乎很常见?有没有人经历过这个?我已经搜索过了......先谢谢!!!!

Karaf版本2.4.0.redhat-630310 骆驼2.17.0.redhat-630310

尝试首先进行身份验证,获取access_token,然后使用access_token访问具有使用权限的系统资源。如何使用JAXB注释将JSON(无根元素)映射到XML?

这是JSON响应:

{"access_token":"eyJhbGciOrZXkiLCJ0eXAiOiJKV1QifQ.","token_type": "bearer","refresh_token":"eyJhbGciXkiLCJ0eXAiOiJKV1QifQ.", "expires_in": 86399, "scope": "password.write openid","jti":75dcd85bd1247b4968f8802e54a9cc1"}

我的POJO模型类

package com.ge.dig.predix.entities;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Entities {

@XmlElement(name="access_token")
private String access_token;
@XmlElement(name="token_type")
private String token_type;
@XmlElement(name="refresh_token")
private String refresh_token;
@XmlElement(name="expires_in")
private String expires_in;
@XmlElement(name="scope")
private String scope;
@XmlElement(name="jti")
private String jti;

public String getAccessToken() {
    return access_token;
}
public void setAccessToken(String access_token) {
    this.access_token = access_token;
}
public String getTokenType() {
    return token_type;
}
public void setTokenType(String token_type) {
    this.token_type = token_type;

...

1 个答案:

答案 0 :(得分:0)

由于我只关心JSON,我将使用Jackson Annotations。但是,我仍然想了解如何使用XML解析。如果有人知道,请指教。谢谢!

所以,这是我支持JSON的JSON映射实体类。

package com.myapp.entities;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;

@JsonIgnoreProperties({ "token_type", "scope", "jti" })
public class TokenEntities {

private String access_token;
private String token_type;
private String refresh_token;
private String expires_in;
private String scope;
private String jti;

@JsonCreator
public TokenEntities(@JsonProperty("access_token") String access_token,
                     //@JsonProperty("token_type")String token_type,
                     @JsonProperty("refresh_token")String refresh_token,
                     @JsonProperty("expires_in")int expires_in,
                     //@JsonProperty("scope")String scope,
                     //@JsonProperty("jti")String jti) {
    this.access_token = access_token;
    //this.token_type = token_type;
    this.refresh_token = refresh_token;
    this.expires_in = expires_in;
    //this.scope = scope;
    //this.jti = jti;
}

public String getAccessToken() {
    return access_token;
}

public String getTokenType() {
    return token_type;
}

public String getRefreshToken() {
    return refresh_token;
}

public int getExpires_in() {
    return expires_in;
}

public String getScope() {
    return scope;
}

public String getJti() {
    return jti;
}
}