jackson中自定义处理序列化和反序列化
对于一直用gson的人来说,如果单独用jackson,真是麻烦了,但还是得小结下了:
先来看下如何自定义把某个对象序列化为json:
先是对象:
public class User { public int id; public String name;}public class Item { public int id; public String itemName; public User owner;}
public class ItemSerializer extends JsonSerializer<Item> { @Override public void serialize(Item value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeNumberField("id", value.id); jgen.writeStringField("itemName", value.itemName); jgen.writeNumberField("owner", value.owner.id); jgen.writeEndObject(); }}
Item myItem = new Item(1, "theItem", new User(2, "theUser"));ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule();module.addSerializer(Item.class, new ItemSerializer());mapper.registerModule(module); String serialized = mapper.writeValueAsString(myItem);
@JsonSerialize(using = ItemSerializer.class)public class Item { ...}
Item myItem = new Item(1, "theItem", new User(2, "theUser"));String serialized = new ObjectMapper().writeValueAsString(myItem);
public class User { public int id; public String name;}public class Item { public int id; public String itemName; public User owner;}
public class ItemDeserializer extends JsonDeserializer<Item> { @Override public Item deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode node = jp.getCodec().readTree(jp); int id = (Integer) ((IntNode) node.get("id")).numberValue(); String itemName = node.get("itemName").asText(); int userId = (Integer) ((IntNode) node.get("id")).numberValue(); return new Item(id, itemName, new User(userId, null)); }}ObjectMapper mapper = new ObjectMapper();SimpleModule module = new SimpleModule();module.addDeserializer(Item.class, new ItemDeserializer());mapper.registerModule(module); Item readValue = mapper.readValue(json, Item.class);