8

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":"foo@bar.com",
   "company":"FooBar"
}

But what I'd like is the following:

[
   "cec34b58",
   "foo",
   "bar",
   "foo@bar.com",
   "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.

Jaims
  • 1,515
  • 2
  • 17
  • 30

3 Answers3

13

This does NOT require custom serializers but simple annotation:

@JsonFormat(shape=JsonFormat.Shape.ARRAY)
public class UserModel {
    // ...
}
StaxMan
  • 113,358
  • 34
  • 211
  • 239
  • 1
    Glad I was able to help! I do wish it came better known, it is indeed neat for some use cases; can compress message sizes for closely-coupled systems. – StaxMan Jan 12 '17 at 22:23
  • 1
    See also the [JsonPropertyOrder](https://fasterxml.github.io/jackson-annotations/javadoc/2.8/com/fasterxml/jackson/annotation/JsonPropertyOrder.html) annotation. – Raedwald Jun 02 '21 at 06:34
0

Your scheme is fairly custom, so you'll have to do via custom serializer thing.

Please also note that I would suggest you to revise it as adding / removing new field / changing order would be much trickier in this case especially if you can't release both client and server simultaneously.

Ivan
  • 3,781
  • 16
  • 20
0

You could add a method toList() and fromList() on your class UserModel that converts your class to/from a List. Instead of serializing your UserModel object with Jackson, you serialize the list.

toongeorges
  • 1,844
  • 17
  • 14