Suresh
Suresh

Reputation: 25

ObjectMapper Custom serializer for serializing a List<User> to User object

I've below Group and User Model objects

 public class Group {
            List<User> user;
        }
    
        public class User {
            String title;
        }

I'm using Jackson to serialize this Group Object. I want to return single User object in the response instead of returning List<User> array. Basically I want to convert List<User> to User to send User as an object in the json response instead of list. I can not use @Jsonserelize annotation serialize the List data to object due to modal objects are generated from external schema.

I know that I can use below annotation to apply converter but unfortunately in my case, modal classes are generated from external schema and I do not have option to add below annotation.

@JsonSerialize(converter = ListUserConverter.class)
List<User> user;

I thought I could add something like below however getting compile time and looks like not supported for List of specific type.

 simpleModule.addSerializer(List<User>.class, new StdDelegatingSerializer(new ListUserConverter()));

public class ListUserConverter extends StdConverter<List<User>, User> {
    @Override
    public User convert(List<User> users) {
        return users.get(0);
    }
}

Is there any another way to apply custom converter specific List to convert list to object?

How do I serialize only List to User (get first object from list) with out annotation usage?

Upvotes: 0

Views: 211

Answers (0)

Related Questions