Search code examples
javajsonjacksonjackson2jackson-databind

Jackson, deserialize plain JSON array to a single Java object


An external service is providing a JSON array with plain/primitive elements (so without field names, and without nested JSON objects). For example:

["Foo", "Bar", 30]

I would like to convert this to an instance of the following Java class using Jackson:

class Person {
    private String firstName;
    private String lastName;
    private int age;

    Person(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }
}

(This class can be adapted if needed.)

Question: is it possible to deserialize this JSON to Java using something like this?

Person p = new ObjectMapper().readValue(json, Person.class);

Or is this only possible by writing a custom Jackson deserializer for this Person class?

I did try the following, but that didn't work:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class Person {
    private String firstName;
    private String lastName;
    private int age;

    @JsonCreator
    public Person(
            @JsonProperty(index = 0) String firstName, 
            @JsonProperty(index = 1) String lastName, 
            @JsonProperty(index = 2) int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public static void main(String[] args) throws IOException {
        String json = "[\"Foo\", \"Bar\", 30]";
        Person person = new ObjectMapper().readValue(json, Person.class);
        System.out.println(person);
    }
}

Result: Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Argument #0 of constructor [constructor for Person, annotations: {interface com.fasterxml.jackson.annotation.JsonCreator=@com.fasterxml.jackson.annotation.JsonCreator(mode=DEFAULT)}] has no property name annotation; must have name when multiple-parameter constructor annotated as Creator at [Source: (String)"["Foo", "Bar", 30]"; line: 1, column: 1]


Solution

  • You don't need @JsonCreator, just use @JsonFormat(shape = JsonFormat.Shape.ARRAY)

    @JsonFormat(shape = JsonFormat.Shape.ARRAY)
    public static class Person {
        @JsonProperty
        private String firstName;
        @JsonProperty
        private String lastName;
        @JsonProperty
        private int age;
    }
    

    And use @JsonPropertyOrder({"firstName", "lastName", "age" } ) if you need to preserve some alternative field declaration order in your bean.