使用Jackson自定义序列化操作(Jackson – Custom Serializer)

目录

    • Standard Serialization of an Object Graph
    • Custom Serializer on the ObjectMapper
    • Custom Serializer on the Class

Standard Serialization of an Object Graph

@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"}}

Custom Serializer on the ObjectMapper

@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}

Custom Serializer on the Class

@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

你可能感兴趣的:(Baeldung,学习笔记,基础知识,mysql,数据库,java)