Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson: Serializing object fields to array

Tags:

java

json

jackson

I'm pretty new to Jackson, but I stumbled upon the following problem:

I'd like to serialize a simple object to an array of its fields. So considering the following class:

public class UserModel {
    private String id;
    private String firstName;
    private String lastName;
    private String email;
    private String company;
}

I get the following json:

{
   "id":"cec34b58",
   "firstName":"foo",
   "lastName":"bar",
   "email":"[email protected]",
   "company":"FooBar"
}

But what I'd like is the following:

[
   "cec34b58",
   "foo",
   "bar",
   "[email protected]",
   "FooBar"
]

I'd like to avoid using a custom serializer if there's an easier way. Reading the Jackson Annotations, I don't immediately see something that allows immediate conversion of the model. Google only advises serialization of Java's Collections to json but nothing to go from a Java Object to a json array.

like image 823
Jaims Avatar asked Jan 06 '17 12:01

Jaims


1 Answers

This does NOT require custom serializers but simple annotation:

@JsonFormat(shape=JsonFormat.Shape.ARRAY)
public class UserModel {
    // ...
}
like image 188
StaxMan Avatar answered Oct 20 '22 22:10

StaxMan