【问题标题】:Vert.x Json.decodeValue listVert.x Json.decodeValue 列表
【发布时间】:2017-05-20 02:14:21
【问题描述】:
有人知道如何在 vert.x 中将 json 字符串解码为 List<Foo> 吗?
您可以使用Json.decodeValue(data, Foo.class); 轻松地将字符串转换为对象,但我似乎不知道如何在列表的情况下这样做。
到目前为止,我已经通过Json.decodeValue(data, List.class); 获取了数据,但除了打印出来之外,您无法对结果做任何事情。
【问题讨论】:
标签:
java
json
list
decode
vert.x
【解决方案1】:
你必须声明一个容器对象,否则,这很简单:
// This is your Foo
public class MyObj {
public String key;
// Just for clarity
@Override
public String toString() {
return "MyObj{" +
"key='" + this.key + '\'' +
'}';
}
}
// This is the container
public class MyArray {
// Property is mandatory in this case
@JsonProperty("objs")
List<MyObj> objs;
}
现在是解析
public static void main(final String[] args) {
// Your input is a JSON array, not a JSON object
final String input = "[{\"key\":\"a\"}, {\"key\":\"b\"}, {\"key\":\"c\"}]";
// We format it to be a JSON object, so we can parse it
final MyArray res = Json.decodeValue(String.format("{\"objs\":%s}", input), MyArray.class);
// Get your List out
System.out.println(res.objs);
}
【解决方案2】:
试试这个
List<Foo> fooList = Json.decodeValue(bodyAsString, new TypeReference<List<Foo>>(){});
TypeReference 是 Jackson 参考资料,供您参考