Parsing JSON Arrays as Objects with Jackson
In this article, I’ll describe a trick from the Jackson JSON parsing library that allows parsing non-typical JSON with greater flexibility.
Sometimes you can’t influence the structure of JSON that you get — for instance, you work with legacy data or consume it from another system. When parsing a record of a person, you usually expect something like this:
{
"name" : "Jane Smith",
"rate" : 4.2,
"age" : 42
}
However, you might get all properties of a person just as elements of an array, without property names:
[
"Jane Smith",
4.2,
42
]
The first element of the array is always a string, the second is a floating-point value, and the third one is an integer. In Java code, you’ll most likely want to model it as an object with fields of proper types, let’s call it Person:
class Person {
private String name;
private Double rate;
private Integer age;
// getters and setters omitted
}
But if you try to parse it like that using the Jackson library, you’ll get an error — a JSON object with properties is expected based on that model, but you try to parse an array (in this code snippet, I use Java text block syntax from Java 13 and var keyword from Java 11):
var objectMapper = new ObjectMapper();
var person = objectMapper.readValue("""
["Jane Smith", 4.2, 42]
""", Person.class);
This is a typical error that you get in such a case:
Cannot deserialize value of type `Person` from Array value (token `JsonToken.START_ARRAY`)
at [Source: (String)" ["Jane Smith", 4.2, 42]
"; line: 1, column: 5]
To fix this, you can add the following two annotations to the model class. The @JsonFormat annotation with shape parameter specifies that you expect this object as a JSON array:
@JsonFormat(shape = JsonFormat.Shape.ARRAY)
The @JsonPropertyOrder annotation describes the order of the object properties in the array:
@JsonPropertyOrder({ "name", "rate", "age" })
So here’s how your model class would look like:
@JsonFormat(shape = JsonFormat.Shape.ARRAY)
@JsonPropertyOrder({ "name", "rate", "age" })
class Person {
private String name;
private Double rate;
private Integer age;
// getters and setters omitted
}
If you now try to deserialize JSON using this class as a target, you’ll get what you expect:
var person = objectMapper.readValue("""
["Jane Smith", 4.2, 42]
""", Person.class);
System.out.println(person2.getName()); // -> "Jane Smith"
System.out.println(person2.getRate()); // -> 4.2
System.out.println(person2.getAge()); // -> 42
Hopefully, this small tip will help you out when parsing non-standard JSON data.