Max Schmidt
Max Schmidt

Reputation: 7655

How to converting a Java List in a Java Map when serializing to JSON with Jackson

I have a List with Person's in Java and each person has an id:

class Person{
  public int id;
  public String name;
}

Now I like to serialize this list in a JSON like that:

{
  "1":{
    "name": "tom"
  },{
  "2":{
    "name": "bob"
  }
}

Is there any anotation for the class which contains the list, to specify the JSON structure?

Thanks.

Upvotes: 3

Views: 408

Answers (2)

StaxMan
StaxMan

Reputation: 116472

One possibility is that if you always want Persons to be serialized this way, you can add custom serializer for type, and register that. There are multiple ways to do this: either use SimpleModule to register it, or use @JsonSerialize(using=PersonSerializer.class) on Person class (this annotation can also be used on properties; property one will have precedence if both defined).

Upvotes: 2

HJW
HJW

Reputation: 23443

To accomplish the above strictly using the Person class, you need

  1. To use a map
  2. Another class to represent the name
class PersonName{
  String name;
}

Map<int, String> map = new HashMap<int, String>();

map.put(person.getId(), personName);

Upvotes: 1

Related Questions