Vert.x Json.decodeValue 列表

Vert.x Json.decodeValue list

有谁知道如何将 json 字符串解码为 vert.x 中的 List<Foo>

您可以使用 Json.decodeValue(data, Foo.class); 轻松地将字符串转换为对象,但我似乎不知道如何在列表的情况下这样做。

到目前为止,我已经通过 Json.decodeValue(data, List.class); 获取了数据,但除了打印出来之外,您无法对结果做任何事情。

Jsonclass使用Jackson解码字符串

我建议您使用 Foo[] 而不是 List。如果你真的需要一个列表,你可以很容易地创建一个 "Arrays.asList(arr)".

或者您可以使用本网站上的示例之一:http://www.baeldung.com/jackson-collection-array

您必须声明一个容器对象,除此之外,这很简单:

// 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);
}

试试这个

List<Foo> fooList = Json.decodeValue(bodyAsString, new TypeReference<List<Foo>>(){});

TypeReference 是供您参考的 Jackson 参考