3

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.

3
  • You cannot do it. if you serialize the list it will looks like : Commented Dec 6, 2011 at 17:03
  • @Jaroslaw.zawila I hoped in Jackson there is an annotation like XmlJavaTypeAdapter in jaxb Commented Dec 6, 2011 at 17:18
  • You can define custom serializer (and deserializer if you need it back) using @JsonSerialize(contentUsing=MySerializer.class); (contentUsing because it's to be used for List values, not List itself) Commented Dec 8, 2011 at 18:29

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

Comments

1

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);

1 Comment

Thanks for your answer. Because I want to keep the List I added a method "getPersonsAsMap()" which converts the list to a map. I annotated this method with "JsonProperty" and the method to getting the list with "JsonIgnore". Finally only the map would be serialized.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.