英文:
Jackson parse array with both anonymous and named field
问题
@ JsonFormat(shape = JsonFormat.Shape.ARRAY)
public class Event {
@JsonProperty
String event;
@JsonProperty("event-id")
String eventId;
@JsonProperty
Map<String, Object> properties;
@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);
}
}
}
英文:
I would like to parse the following json string using Jackson ObjectMapper:
["EVENT","event-id",{"content":"{}","created_at":1677781808,"tags":[["t","tag1"]]}]
I was trying the following model class:
@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);
}
}
}
Trying to parse like this:
Event event = mapper.readValue(message.getPayload().getBytes(StandardCharsets.UTF_8), Event.class);
I get the following error:
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":...
答案1
得分: 1
你可以在你的 Event
类上添加 JsonIgnoreProperties
注解,以忽略在反序列化期间不包含在你的类中的 JSON 属性的处理:
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonFormat(shape = JsonFormat.Shape.ARRAY)
public class Event {
String event;
String eventId;
}
Event event = mapper.readValue(message.getPayload()
.getBytes(StandardCharsets.UTF_8), Event.class);
// 输出结果为 [ "EVENT", "event-id" ]
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(event));
在上述代码中,Event
类使用 @JsonIgnoreProperties
注解,设置 ignoreUnknown
为 true
,以便忽略不包含在类中的 JSON 属性。
英文:
You can add the JsonIgnoreProperties
annotation to your Event
class so ignoring the processing of JSON properties not included in your class read during deserialization:
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonFormat(shape= JsonFormat.Shape.ARRAY)
public class Event {
String event;
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));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论