使用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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值