簡體   English   中英

通過RestTemplate postForObject將JSON葉映射到對象

[英]Map JSON leaf to an object via RestTemplate postForObject

使用restful api返回一個json字符串。 格式是

{
  "status": "ok",
  "result": { <the method result> }
}

我正在嘗試將用戶配置文件的響應映射到UserProfile.class

MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
parameters.set("method", "currentUser");
URI url = buildUri("users/show.json");
UserProfile profile = this.getRestTemplate().postForObject(url, parameters, UserProfile.class );

用戶個人資料包含響應結果中的所有字段。 如果我添加字段字符串狀態,UserProfile結果,它將UserProfile映射到結果,我可以從那里提取它,但這感覺有點不對。

我希望postForObject函數將JSON響應相關葉“結果”映射到UserProfile.class

對我來說,最明智的方法是將響應結果映射到包含用戶配置文件對象的對象。 您可以避免不必要的復雜化進行自定義反序列化,並允許您訪問狀態代碼。 您甚至可以將響應結果對象設為通用,以便它適用於任何類型的內容。

以下是使用Jackon的對象映射器的示例。 在Spring中,您需要使用ParameterizedTypeReference來傳遞泛型類型信息(請參閱此答案 ):

public class JacksonUnwrapped {

    private final static String JSON = "{\n" +
            "  \"status\": \"ok\",\n" +
            "  \"result\": { \"field1\":\"value\", \"field2\":123 }\n" +
            "}";


    public static class Result<T> {
        public final String status;
        public final T result;

        @JsonCreator
        public Result(@JsonProperty("status") String status,
                      @JsonProperty("result") T result) {
            this.status = status;
            this.result = result;
        }

        @Override
        public String toString() {
            return "Result{" +
                    "status='" + status + '\'' +
                    ", result=" + result +
                    '}';
        }
    }

    public static class UserProfile {
        public final String field1;
        public final int field2;

        @JsonCreator
        public UserProfile(@JsonProperty("field1") String field1,
                           @JsonProperty("field2") int field2) {
            this.field1 = field1;
            this.field2 = field2;
        }

        @Override
        public String toString() {
            return "UserProfile{" +
                    "field1='" + field1 + '\'' +
                    ", field2=" + field2 +
                    '}';
        }
    }

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        Result<UserProfile> value = mapper.readValue(JSON, new TypeReference<Result<UserProfile>>() {});
        System.out.println(value.result);
    }

}

輸出:

UserProfile{field1='value', field2=123}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM