jackson将数组反序列化为java对象
我有第三方编码的json’ed host, port, uri
元组数组作为固定长度数组的数组:
[ ["www1.example.com", "443", "/api/v1"], ["proxy.example.com", "8089", "/api/v4"] ]
我想用jackson magic获取一个实例列表
class Endpoint { String host; int port; String uri; }
请帮我设置正确的注释,使ObjectMapper能够发挥魔力。
我无法控制传入的格式,所有我的google’n都以如何将正确的json对象(不是数组)数组映射到对象列表(如https://stackoverflow.com/a/6349488/707608 )的答案结束)
=== https://stackoverflow.com/users/59501/staxman在https://stackoverflow.com/a/38111311/707608建议的工作解决方案
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 endpoints = om.readValue(input, new TypeReference<List>() {}); 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 + '\'' + '}'; } }
添加以下注释:
@JsonFormat(shape=JsonFormat.Shape.ARRAY) class Endpoint { }
并且它应该按照您的意愿序列化条目。
另外:最安全的是使用@JsonPropertyOrder({ .... } )
来强制执行特定的排序,因为JVM可能会或可能不会以任何特定顺序公开字段或方法。
考虑导入二维数组,然后运行循环。 然后,您可以在Endpoint类上拥有一个构造函数,该构造函数接受内部数组的每个实例。