在Spring Boot项目中使用Jackson反序列化JSON时,一个字段被指定为null

时间:2017-11-14 13:57:48

标签: java json spring jackson

我正在使用Spring <?php /* Plugin Name: Combined Plugin Description: Contains plugin a, plugin b and plugin c */ include dirname(__FILE__) . '/plugin-a.php'; include dirname(__FILE__) . '/plugin-b.php'; include dirname(__FILE__) . '/plugin-c.php'; ?> 调用外部API。返回的JSON具有以下内容。

restTemplate

除了我屏蔽的那些{ "message": null, "responseStatus": "0", "accessInfo": { "access": { "message": "success", "token": { "expires": "xxxxx", "id": null, "UDID": null, "permissions": { "orgGroups": [], "channelGroups": [ "xxxxx" ] } } } }, "profile": { "message": null, "responseStatus": null, "UDID": "xxxxx", "name": null, "age": null, "gender": null, "maritalStatus": null, "familySize": null, "lat": null, "lon": null, "birthDay": null, "imageURL": null, "sessionId": "xxxxx", "FBId": null, "expiry": null, "email": "xxxxx", "workLocationLat": null, "workLocationLong": null, "workLocationAddress": null, "homeLocationAddress": null, "homeLocationLat": null, "homeLocationLong": null, "id": 789, "isFBIdAlreadyExists": false, "tagList": [] } } 之外,所有值都是真正返回的值。如您所见,JSON中有两个xxxxx字段。一个在节点UDID&gt; accessInfo&gt; access token和节点null中的另一个profile。第二个节点中的值是我感兴趣的值,不应该是null

我创建了2个POJO,如下所示。我只对UDID节点下的sessionIdprofile感兴趣。

父POJO:

@JsonIgnoreProperties(ignoreUnknown = true)
public class AgtAuthentication {

    private Profile profile;

}

儿童POJO:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Profile {

    private String sessionId;
    private String UDID;

}

为了简洁,我删除了getter和setter,没有args构造函数。

当我调用Api时,我收到响应并且JSON映射工作正常,但UDID属性除外。当我为响应主体做System.out.println()时,我得到以下结果:

Authentication [profile = Profile [sessionId = xxxxx, UDID = null]]

sessionId是正确的。但是,UDID始终为null。不确定这是否是因为JSON中存在重复的UDID值。有人可以帮忙吗?感谢。

编辑:调用实际Api(xxxxx被屏蔽的值)的代码如下:

private void setUuidAndSessionId() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> requestBody= new LinkedMultiValueMap<String, String>();
        requestBody.add("clientId", "xxxxx");
        requestBody.add("clientPassword", "xxxxx");
        requestBody.add("UDID", "");
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(requestBody, headers);

        RestTemplate restTemplate = new RestTemplate();

        String agtAuthUrl = "http://xxxxx";

        ResponseEntity<AgtAuthentication> response = restTemplate.exchange(agtAuthUrl, HttpMethod.POST, request, AgtAuthentication.class);

        System.out.println(response.getBody().toString());

        sessionId = response.getBody().getProfile().getSessionId();
        String tempUuid = response.getBody().getProfile().getUDID();
    }

1 个答案:

答案 0 :(得分:1)

我假设Jackson希望JSON中的字段名为uDID - 因为getter / setter方法命名约定将第一个字母字母转换为大写。

您可以尝试使用Profile.getUDID()

注释@JsonProperty("UDID") getter