2

Does anyone know how to decode a json string to List<Foo> in vert.x?

You can convert a string to object easily with Json.decodeValue(data, Foo.class); but I can't seem to figure out how to do so in case of lists.

So far I've gotten the data out with Json.decodeValue(data, List.class); but you can't really do anything with the result apart from print it out.

Rauno
  • 616
  • 8
  • 22
  • I had to use the `Gson.fromJson` API for lists. http://stackoverflow.com/questions/18544133/parsing-json-array-into-java-util-list-with-gson/18547661#18547661 – Leif Gruenwoldt Mar 02 '17 at 18:54

3 Answers3

2

You'll have to declare a container object, but otherwise, it's quite simple:

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

And now the parsing

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);
}
Alexey Soshin
  • 16,718
  • 2
  • 31
  • 40
2

Try this

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

TypeReference is Jackson reference for your information

Sandeep Tengale
  • 152
  • 4
  • 13
-1

The Json class use Jackson to decode the string.

I recommend you to use a Foo[] instead of a List. If you really need a List, you can easily create one "Arrays.asList(arr)".

Or you can use one of the examples on this site: http://www.baeldung.com/jackson-collection-array