Java JSON对象

时间:2018-01-08 10:25:13

标签: java json

我使用Java从REST服务中检索一些JSON。我喜欢的是映射JSON" node"到Java对象。

JSON是这样的:

{  
   "token":{  
      "tokenType":"Bearer",
      "accessToken":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MTU0MDY0MjgsImlhdCI6MTUxNTQwNTUyOCwic3ViIjoiNWE1MzQwZDg4NmUxYTc2ZGU2MTY2NTQ2In0.7YjmghgAQLtyNaPuWDp9StQBJv79JQZD3G_XbKvYOaQ",
      "refreshToken":"5a5340d886e1a76de6166546.35e821dd2042efad2add8da80d6c765bded3ca37078415a4ebe46f9ba8da312a6d16cc05e91431bc",
      "expiresIn":"2018-01-08T10:13:48.261Z"
   },
   "user":{  
      "id":"5a5340d886e1a76de6166546",
      "email":"testingsest@gmail.com",
      "role":"user",
      "createdAt":"2018-01-08T09:58:48.153Z"
   }
}

Token.java就像:

public class Token {

    String tokenType;
    String accessToken;
    String refreshToken;
    long expiresIn;

    public String getTokenType() {
        return tokenType;
    }

    public void setTokenType(String tokenType) {
        this.tokenType = tokenType;
    }

    public String getAccessToken() {
        return accessToken;
    }

    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }

    public String getRefreshToken() {
        return refreshToken;
    }

    public void setRefreshToken(String refreshToken) {
        this.refreshToken = refreshToken;
    }

    public long getExpiresIn() {
        return expiresIn;
    }

    public void setExpiresIn(long expiresIn) {
        this.expiresIn = expiresIn;
    }


}

如何映射"令牌"使用Jackson库(使用ObjectMapper)进入Object?

(我知道如何手动解析JSON并在Token类中手动填充setter方法)

1 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

首先,创建一个User类:

public class User {

    private String id;

    private String email;

    private String role;

    private String createdAt;

    //constructors and getters/setters
}

创建你的包装类(这里我把它命名为Session):

public class Session {

    private Token token;

    private User user;

    //constructors and getters/setters
}

然后你可以用杰克逊作为Session的一个实例取消收回你收到的对象。

----编辑:

如果您不想在User内映射Session,只需在Session课程中添加以下注释:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Session {

    private Token token;

    //constructors and getters/setters
}