@Data
@NoArgsConstructor
@AllArgsConstructor
public class Item {
public int id;
public String itemName;
public User owner;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
public int id;
public String name;
}
Item myItem = new Item(1, "theItem", new User(2, "theUser"));
String serialized = new ObjectMapper().writeValueAsString(myItem);
System.out.println(serialized);
结果
{"id":1,"itemName":"theItem","owner":{"id":2,"name":"theUser"}}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Item {
public int id;
public String itemName;
public User owner;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
public int id;
public String name;
}
public class ItemSerializer extends StdSerializer<Item> {
public ItemSerializer() {
this(null);
}
public ItemSerializer(Class<Item> t) {
super(t);
}
@Override
public void serialize(Item value, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeNumberField("id", value.id);
jsonGenerator.writeStringField("itemName", value.itemName);
jsonGenerator.writeNumberField("owner", value.owner.id);
jsonGenerator.writeEndObject();
}
}
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(Item.class, new ItemSerializer());
mapper.registerModule(module);
Item myItem = new Item(1, "theItem", new User(2, "theUser"));
String serialized = mapper.writeValueAsString(myItem);
System.out.println(serialized);
结果
{"id":1,"itemName":"theItem","owner":2}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
public int id;
public String name;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonSerialize(using = ItemSerializer.class)
public class Item {
public int id;
public String itemName;
public User owner;
}
Item myItem = new Item(1, "theItem", new User(2, "theUser"));
String serialized = new ObjectMapper().writeValueAsString(myItem);
System.out.println(serialized);
结果
{"id":1,"itemName":"theItem","owner":2}
-----------------------------------------------------------------------------读书笔记摘自 文章:Jackson – Custom Serializer