Jackson 解析具有匿名和命名字段的数组

问题描述 投票:0回答:1

我想使用 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":...
json jackson
1个回答
0
投票

您可以将

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));
© www.soinside.com 2019 - 2024. All rights reserved.