我是一个模型对象组
public class Group {
String title;
List<User> members;
String createdBy;
}
我使用Jackson来序列化这个对象。而不是序列化列表中的整个用户对象&#34;成员&#34;我想序列化user.getTitle()
字段。
基本上我希望HashMap类似于
{
"title" : "sometitle"
"members" : [user1.getTitle(), user2.getTitle()]
}
我已为此
编写了自定义序列化程序public class GroupSerializer extends JsonSerializer<Circle> {
@Override
public void serialize(Group value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
if(value != null) {
gen.writeStartObject();
gen.writeStringField("title", value.getTitle());
gen.writeStringField("createdBy", value.getCreatedBy());
gen.writeFieldName("members");
gen.writeStartArray();
for(User user : value.getMembers()) {
gen.writeString(user.getEmail());
}
gen.writeEndArray();
gen.writeEndObject()
}
}
}
但它没有用。如何仅序列化List的字段而不是整个用户对象?
答案 0 :(得分:11)
我建议您查看Jackson的Converter
界面,这似乎比创建自定义序列化程序更适合该任务。
创建Converter
实例并将其添加到ObjectMapper
的一种方法,以便它将用于序列化所有User
个实例。
public class UserConverter extends StdConverter<User, String> {
@Override
public String convert(User user) {
return user.getTitle();
}
}
在ObjectMapper
上注册,如下所示:
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(User.class, new StdDelegatingSerializer(new UserConverter()));
ObjectMapper om = new ObjectMapper().registerModule(simpleModule);
如果您不想将所有User
个实例转换为String
,另一种方法是使用如下转换器为所选属性添加注释:
public class Group {
String title;
@JsonSerialize(converter = ListUserConverter.class)
List<User> members;
String createdBy;
}
并且有一个相应的转换器,看起来像这样:
public class ListUserConverter extends StdConverter<List<User>, List<String>> {
@Override
public List<String> convert(List<User> users) {
return users.stream().map(User::getTitle).collect(Collectors.toList());
}
}
答案 1 :(得分:1)
尝试如下:
组:
@JsonIgnoreProperties(ignoreUnknown=true)
public class Group {
@JsonSerialize(using= TitleSerializer.class)
List<User> members;
//getters and setters
}
用户:
public class User {
private String title;
//getters and setters
}
自定义序列化程序:
public class TitleSerializer extends StdSerializer<List<User>> {
private static List<User> users=new ArrayList<User>();
protected TitleSerializer(Class<List<User>> t) {
super(t);
// TODO Auto-generated constructor stub
}
@SuppressWarnings("unchecked")
public TitleSerializer(){
this((Class<List<User>>) users.getClass());
}
@Override
public void serialize(List<User> users, JsonGenerator paramJsonGenerator,
SerializerProvider paramSerializerProvider) throws IOException {
paramJsonGenerator.writeStartObject();
List<String> titles=new ArrayList<String>(users.size());
for(User user: users){
titles.add(user.getTitle());
}
paramJsonGenerator.writeObjectField("members", titles);
paramJsonGenerator.writeEndObject();
}
}
测试:
Group group=new Group(Arrays.asList(new User("a"),new User("b"),new User("c")));
ObjectMapper mapper = new ObjectMapper();
String serialized = mapper.writeValueAsString(group);
System.out.println("output "+serialized);
输出:
{"members":["a","b","c"]}