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

Maven依赖

<dependencies>
    <!-- yaml -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.14.2</version>
        <exclusions>
            <exclusion>
                <artifactId>jackson-annotations</artifactId>
                <groupId>com.fasterxml.jackson.core</groupId>
            </exclusion>
            <exclusion>
                <artifactId>jackson-core</artifactId>
                <groupId>com.fasterxml.jackson.core</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-yaml</artifactId>
        <version>2.14.2</version>
        <exclusions>
            <exclusion>
                <artifactId>jackson-core</artifactId>
                <groupId>com.fasterxml.jackson.core</groupId>
            </exclusion>
            <exclusion>
                <artifactId>jackson-databind</artifactId>
                <groupId>com.fasterxml.jackson.core</groupId>
            </exclusion>
            <exclusion>
                <artifactId>snakeyaml</artifactId>
                <groupId>org.yaml</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.yaml</groupId>
        <artifactId>snakeyaml</artifactId>
        <version>2.0</version>
    </dependency>
    <!--Json相关-->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.14.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.15.1</version>
    </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

猜你喜欢

转载自blog.csdn.net/weixin_37646636/article/details/132092222