2016-12-14 101 views
0

在以下的代碼,如何合併兩個不同類型的json文件?

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" 
} 
+0

你的意思是[像這樣(http://stackoverflow.com/questions/9895041/merging-two-json-documents-using-jackson)? – dnault

+0

@dnault有點,但示例顯示兩個對象具有相同的返回類型(MyBean),我有兩種不同的類型(String和SessionValidationResponse)。感謝您的回覆。 :) –

回答

0

找到了解決方案。我將這兩個值轉換成一個HashMap,並使用Map將它們合併到一個使用putAll(map1, map2);的單個(新)Map中。