如何合并两个具有不同类型的json文件?

时间:2016-12-14 20:26:17

标签: java json dictionary collections casting

在下面提到的代码中,

String additionalAttributes = new ObjectMapper().writeValueAsString(retrieveAttributes(requestApplication));

" additionalAttributes"给我第一个json响应,sessionValidationResponse给了我另一个json响应,请注意两者都有不同的返回类型(String和SessionValidationResponse) 如何合并这些响应以发送单个json响应

public SessionValidationResponse checkToken(String tokenId) throws RuntimeException {
    System.out.println(" \n \n \n Enter in checkToken method");
    System.out.println("Received Token ID: " + tokenId);


    if (null != tokenId && tokenId != "") {
        try {


            String filepath = "session_validation.json";
            String requestApplication = "myVf";
            String additionalAttributes = new ObjectMapper().writeValueAsString(retrieveAttributes(requestApplication));
            System.out.println("additionalAttributes: " +additionalAttributes);


            try {
                SessionValidationResponse sessionValidationResponse = jsonFileReader.read(filepath, new TypeReference<SessionValidationResponse>() {
                });
                sessionValidationResponse.setToken(createToken(sessionValidationResponse.getUserName(), new Date(), Calendar.getInstance().getTime()));
                return sessionValidationResponse;
            } catch (Exception e) {
                throw new RuntimeException();
            }


        } catch (SignatureException e) {
            throw new InvalidTokenException(new Exception(INVALID_TOKEN));
        } catch (ExpiredJwtException e) {
            throw new TokenExpirationException(new Exception(TOKEN_EXPIRED));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    } else {
        throw new TokenEmptyException(new Exception(TOKEN_NOT_FOUND));
    }
    return null;
}

字符串类型的响应:{"status":"ACTIVE","msisdn":"45695","UT_MOBILE":"4258963144","gender":"MALE"}

SessionValidationResponse类型的响应

{
  "valid": true,
  "uid": "demo",
  "userName": "ABC",
  "token": "randomToken",
  "msisdn": "9949999499"
}

1 个答案:

答案 0 :(得分:0)

找到解决方案。我将这两个值都转换为HashMap,然后使用Map将它们合并为一个(新的)Map {/ 1}}。