我有host, port, uri第三方编码的json'ed 元组数组作为固定长度数组的数组:
[
["www1.example.com", "443", "/api/v1"],
["proxy.example.com", "8089", "/api/v4"]
]
Run Code Online (Sandbox Code Playgroud)
我想用杰克逊魔法获取一个实例列表
class Endpoint {
String host;
int port;
String uri;
}
Run Code Online (Sandbox Code Playgroud)
请帮我添加正确的注释,使ObjectMapper能够发挥作用.
我无法控制传入的格式,所有我的google'n都以如何将正确的json对象(不是数组)数组映射到对象列表(如/sf/answers/444464191/)的答案结束)
= /sf/users/4165101/ 在/sf/answers/2667791801/中建议的工作解决方案
public static void main(String[] args) throws IOException {
String input = "" +
"[\n" +
" [\"www1.example.com\", \"443\", \"/api/v1\"],\n" +
" [\"proxy.example.com\", \"8089\", \"/api/v4\"]\n" +
"]";
ObjectMapper om = new ObjectMapper();
List<Endpoint> endpoints = om.readValue(input,
new TypeReference<List<Endpoint>>() {});
System.out.println("endpoints = " + endpoints);
}
@JsonFormat(shape = JsonFormat.Shape.ARRAY)
static class Endpoint {
@JsonProperty() String host;
@JsonProperty() int port;
@JsonProperty() String uri;
@Override
public String toString() {
return "Endpoint{host='" + host + '\'' + ", port='" + port + '\'' + ", uri='" + uri + '\'' + '}';
}
}
Run Code Online (Sandbox Code Playgroud)
添加以下注释:
@JsonFormat(shape=JsonFormat.Shape.ARRAY)
class Endpoint {
}
Run Code Online (Sandbox Code Playgroud)
它应该按你的意愿序列化条目.
另外:最安全的是然后使用@JsonPropertyOrder({ .... } )来强制执行特定的排序,因为JVM可能会或可能不会以任何特定顺序公开字段或方法.
| 归档时间: |
|
| 查看次数: |
2255 次 |
| 最近记录: |