gpt4 book ai didi

java - 通过 RestTemplate postForObject 将 JSON 叶映射到对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:24:15 24 4
gpt4 key购买 nike

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

{
"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 );

用户配置文件包含响应结果中的所有字段。如果我添加字段 String status、UserProfile 结果,它将 UserProfile 映射到结果,我可以从那里提取它,但这感觉有点不对。

我希望 postForObject 函数将 JSON 响应相关叶“结果”映射到 UserProfile.class

最佳答案

对我来说,最清晰的方法是将响应结果映射到包含用户配置文件对象的对象。您可以避免在进行自定义反序列化时出现不必要的复杂情况,并允许您访问状态代码。您甚至可以使响应结果对象通用,以便它适用于任何类型的内容。

这是一个使用 Jackon 的对象映射器的示例。在 Spring 中,您需要使用ParameterizedTypeReference 来传递通用类型信息(参见 this answer ):

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}

关于java - 通过 RestTemplate postForObject 将 JSON 叶映射到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24226168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com