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.

1

3 Answers 3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

2

Try this

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

TypeReference is Jackson reference for your information

Comments

-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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.