Jackson: 从String反序列化为Object

2024-12-10

引入依赖

    <dependency>

        <groupId>com.fasterxml.jackson.core</groupId>

        <artifactId>jackson-databind</artifactId>

    </dependency>

配置

 OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

 OBJECT_MAPPER.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

使用

 OBJECT_MAPPER.readValue(jsonStr, clazz);

完整代码参考:

 public class Json {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    static {
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        OBJECT_MAPPER.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    public static <T> T parseJson(String jsonStr, Class<T> clazz) throws JsonProcessingException {
        return OBJECT_MAPPER.readValue(jsonStr, clazz);
    }
}

完整demo

model:

import lombok.Data;

@Data
public class DebeziumChange {

    private Payload payload;

    @Data
    public static class  Payload {
       private Source source;
    }

    @Data
    public static class Source {
        private String db;
        private String table;
    }
}

json字符串:

{
	"payload": {
		"source": {
			"table": "document"
		}
	}
}

转化:

  DebeziumChange change = Json.parseJson(message, DebeziumChange.class);

  String cacheName =  change.getPayload().getSource().getTable();

  输出: document