消费mq时String转Object
for (MessageExt msg : msgs) {
String msgBody = new String(msg.getBody(), StandardCharsets.UTF_8);
BinlogEvent binlogEvent = JsonUtil.silentString2Object(msgBody, BinlogEvent.class);
binlogEvent.setPort(Long.valueOf(port));
tConsumer.consume(binlogEvent);
}
binlogEvent.setPort空指针,说明binlogEvent为空
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.lang.String` from Object value (token `JsonToken.START_OBJECT`)
at [Source: (String)"{ "before": {}, "after": { "id": 1019, "name": "ababababab", "score": 99 }, "source": { "version": "zzcdc:", "connector": "mysql", "name": "zzcdc:task:5017", "ts_ms": 1686193967, "db": "cdc", "table": "t1", "server_id": 192215017, "gtid": "", "file": "", "pos": 0, "row": 0, "partition_key": "5017:cdc:t1:1019" }, "op": "u", "ts_ms": 1686193967808, "transaction": null, "timestamp": "2023-06-08T11:12:47.808178366+08:00", "ts_u_ms": 1686193967808178}"; line: 1, column: 13] (through reference chain: com.zhuanzhuan.datasync.helper.mq.event.BinlogEvent["before"])
Cannot deserialize value of type `java.lang.String` from Object value (token `JsonToken.START_OBJECT`)
报错信息:意思是Object反序列化为String失败
String:
{
"before": {},
"after": {
"id": 1019,
"name": "ababababab",
"score": 99
},
"source": {
"version": "zzcdc:",
"connector": "mysql",
"name": "zzcdc:task:5017",
"ts_ms": 1686193967,
"db": "cdc",
"table": "t1",
"server_id": 192215017,
"gtid": "",
"file": "",
"pos": 0,
"row": 0,
"partition_key": "5017:cdc:t1:1019"
},
"op": "u",
"ts_ms": 1686193967808,
"transaction": null,
"timestamp": "2023-06-08T11:12:47.808178366+08:00",
"ts_u_ms": 1686193967808178
}
承接实体Object:
public class BinlogEvent {
private String before;
private String after;
private String source;
private String op;
private Long tsMs;
private String transaction;
private String timestamp;
private Long tsUMs;
}
发现原因:JSON/Object数据不能用String承接
方法1:使用Object承接
public class BinlogEvent {
private Object before;
private Object after;
private Object source
private String op;
private Long tsMs;
private Object transaction;
private String timestamp;
private Long tsUMs;
}
方法2:新建JSON对应实体类承接
public class BinlogEvent {
private Object before;
private Object after;
private BinlogSourceEvent source
private String op;
private Long tsMs;
private Object transaction;
private String timestamp;
private Long tsUMs;
}
public class BinlogSourceEvent {
private String version;
private String connector;
private String name;
private Long tsMs;
private String db;
private String table;
private Long serverId;
private String gtid;
private String file;
private Long pos;
private Long row;
private String partitionKey;
}