我想使用 Jackson ObjectMapper 解析以下 json 字符串:
["EVENT","event-id",{"content":"{}","created_at":1677781808,"tags":[["t","tag1"]]}]
我正在尝试以下模型类:
@JsonFormat(shape= JsonFormat.Shape.ARRAY)
public class Event {
@JsonProperty
String event;
@JsonProperty
String eventId;
@Override
public String toString() {
ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
try {
String json = mapper.writeValueAsString(this);
return json;
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}
尝试像这样解析:
Event event = mapper.readValue(message.getPayload().getBytes(StandardCharsets.UTF_8), Event.class);
我收到以下错误:
Unexpected token (START_OBJECT), expected END_ARRAY: Unexpected JSON values; expected at most 2 properties (in JSON Array)
at [Source: (byte[])"["EVENT","3c1dbf5f-b2b0-478d-9b18-2721a90d5f29",{"content":...
JsonIgnoreProperties
注释添加到您的 Event
类中,从而忽略在反序列化期间读取的类中不包含的 JSON 属性的处理:
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonFormat(shape= JsonFormat.Shape.ARRAY)
public class Event {
@JsonProperty
String event;
@JsonProperty
String eventId;
}
Event event = mapper.readValue(message.getPayload()
.getBytes(StandardCharsets.UTF_8), Event.class);
//it prints [ "EVENT", "event-id" ]
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(event));