- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
使用返回 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/
我正在尝试从底层叶进程写入命名管道并从顶层进程的管道读取。 为此,我首先在顶级进程中创建 FIFO,然后使用 for 循环派生更多进程。在 for 循环中,我正在检查叶子进程,如果它是叶子,我正在写入
我需要一个XPath表达式来验证XML列表元素是否只有某种类型的节点。 例: 我需要知道列表中是否只有图像。
我想从层次结构表中获取所有叶子及其根。叶子是最低层节点,根是最顶层节点。 给定一棵树: A --B --C --D E --F --G --H 叶子是节点:C, D根是:A、E 该表如下所
尝试从嵌套数组中删除相同的 sibling (叶子)/相同的数组。 例如 $data = [ 'test' => [ 'a' => [
我可以遍历目录并只打印文件夹/目录名称,但我想排除包含其他目录的目录的文件夹名称。出于某种原因,我称其为树结构中的“最终节点”,但我很可能是在自欺欺人,这不是第一次了。 =) 在审查其他答案列表时,也
我现在经常使用 Folium,在 Python 中拥有如此易于使用的东西真的很棒。但是他们的文档严重落后,我理解。所以我有2个问题。 我在尝试获得更多标记颜色时做错了什么?这是我尝试过的:map.si
我正在尝试使用 ape 包中的 plot.phylo 命令为 R 中系统发育类型图的边缘(线)添加颜色。这个例子是一个“粉丝”类型的图,虽然我希望这个方法与“系统图类型”或其他任何东西相同。 libr
我正在尝试呈现一个 JTree 叶以具有包含可编辑 JTextArea 的 JPanel,以便用户可以输入文本并能够在添加文本时向下滚动, 并且还使用包装器来限制文本的宽度,使其向下延伸以留出更多空间
这是要修改的正确 Linux 内核代码吗?我如何进行更改以模拟 CPUID 代码以及我需要更改哪个函数。谢谢 #include #include #include #include #incl
我是一名优秀的程序员,十分优秀!