使用Jackson自定义反序列化操作(Custom Deserialization in Jackson)

目录

    • Maven依赖
    • Standard Deserialization
    • Custom Deserializer on ObjectMapper
    • Custom Deserializer on the Class
    • Custom Deserializer for a Generic Type

Maven依赖

<dependencies>
    
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-databindartifactId>
        <version>2.14.2version>
        <exclusions>
            <exclusion>
                <artifactId>jackson-annotationsartifactId>
                <groupId>com.fasterxml.jackson.coregroupId>
            exclusion>
            <exclusion>
                <artifactId>jackson-coreartifactId>
                <groupId>com.fasterxml.jackson.coregroupId>
            exclusion>
        exclusions>
    dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.dataformatgroupId>
        <artifactId>jackson-dataformat-yamlartifactId>
        <version>2.14.2version>
        <exclusions>
            <exclusion>
                <artifactId>jackson-coreartifactId>
                <groupId>com.fasterxml.jackson.coregroupId>
            exclusion>
            <exclusion>
                <artifactId>jackson-databindartifactId>
                <groupId>com.fasterxml.jackson.coregroupId>
            exclusion>
            <exclusion>
                <artifactId>snakeyamlartifactId>
                <groupId>org.yamlgroupId>
            exclusion>
        exclusions>
    dependency>
    <dependency>
        <groupId>org.yamlgroupId>
        <artifactId>snakeyamlartifactId>
        <version>2.0version>
    dependency>
    
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-coreartifactId>
        <version>2.14.2version>
    dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-annotationsartifactId>
        <version>2.15.1version>
    dependency>

Standard Deserialization

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Item {
    public int id;
    public String itemName;
    public User owner;
}
String json = "{\n" +
        "    \"id\": 1,\n" +
        "    \"itemName\": \"theItem\",\n" +
        "    \"owner\": {\n" +
        "        \"id\": 2,\n" +
        "        \"name\": \"theUser\"\n" +
        "    }\n" +
        "}";
        
Item itemWithOwner = new ObjectMapper().readValue(json, Item.class);

System.out.println(itemWithOwner); 

结果
Item(id=1, itemName=theItem, owner=User(id=2, name=theUser))

Custom Deserializer on ObjectMapper

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    public int id;
    public String name;
}
public class ItemDeserializer extends StdDeserializer<Item> {

    public ItemDeserializer() {
        this(null);
    }


    public ItemDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public Item deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        JsonNode jsonNode = jsonParser.getCodec().readTree(jsonParser);
        
        int id = (Integer) ((IntNode) jsonNode.get("id")).numberValue();
        String itemName = jsonNode.get("itemName").asText();
        int userId = (Integer) ((IntNode) jsonNode.get("createdBy")).numberValue();

        return new Item(id, itemName, new User(userId, null));
    }
}
String json = "{\n" +
        "    \"id\": 1,\n" +
        "    \"itemName\": \"theItem\",\n" +
        "    \"createdBy\": 2\n" +
        "}";
        
ObjectMapper mapper = new ObjectMapper();

SimpleModule module = new SimpleModule();
module.addDeserializer(Item.class, new ItemDeserializer());

mapper.registerModule(module);

Item readValue = mapper.readValue(json, Item.class);

System.out.println(readValue);

结果
Item(id=1, itemName=theItem, owner=User(id=2, name=null))

Custom Deserializer on the Class

在上文ItemDeserializer的基础上

@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonDeserialize(using = ItemDeserializer.class)
public class Item {
    public int id;
    public String itemName;
    public User owner;
}
String json = "{\n" +
        "    \"id\": 1,\n" +
        "    \"itemName\": \"theItem\",\n" +
        "    \"createdBy\": 2\n" +
        "}";
        
Item itemWithOwner = new ObjectMapper().readValue(json, Item.class);
System.out.println(itemWithOwner);

// Item(id=1, itemName=theItem, owner=User(id=2, name=null))

Custom Deserializer for a Generic Type

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Item {
    public int id;
    public String itemName;
    public Wrapper<User> owner;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    public int id;
    public String name;
}
@Data
public class Wrapper<T> {
    T value;

    public T getValue() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }
}
public class WrapperDeserializer extends JsonDeserializer<Wrapper<?>> implements ContextualDeserializer {

    private JavaType type;

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) {
        this.type = property.getType().containedType(0);
        return this;
    }

    @Override
    public Wrapper<?> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, IOException {
        Wrapper<?> wrapper = new Wrapper<>();
        wrapper.setValue(deserializationContext.readValue(jsonParser, type));
        return wrapper;
    }
}
ObjectMapper mapper = new ObjectMapper();

SimpleModule module = new SimpleModule();
module.addDeserializer(Wrapper.class, new WrapperDeserializer());

mapper.registerModule(module);

String json = "{\n" +
              "\"id\": 1,\n" +
              "\"itemName\": \"theItem\",\n" +
              "\"owner\": {\n" +
              "    \"id\": 2,\n" +
              "    \"name\": \"theUser\"\n" +
              "}\n" +
              "}";
              
Item readValue = mapper.readValue(json, Item.class);
System.out.println(readValue);

Item(id=1, itemName=theItem, owner=Wrapper(value=User(id=2, name=theUser)))

-----------------------------------------------------------------------------读书笔记摘自 文章:
Getting Started with Custom Deserialization in Jackson

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