在一个字段中使用JSON数据解析JSON数据

时间:2017-12-13 21:09:33

标签: java json jackson

我已尝试过this question所述的那些方法,但由于某些原因它们并不适用于我。这是一个模型类:

@JsonIgnoreProperties(ignoreUnknown = true)
@AllArgsConstructor
public class LogMessage {    

  @Getter @Setter private String timestamp;
  @Getter @Setter private String level;
  private Object message;
  @Getter @Setter private String loggername;
  @Getter @Setter private String thread;

  @JsonSetter("message")
  public void setMessage(Object data)
  {
    this.message = data;
  }

  @JsonRawValue
  public String getMessage() {
    return this.message == null ? null : this.message.toString();
  }
}

消息字段可以是JSON数据,解析部分代码:

    ObjectMapper objectMapper = new ObjectMapper();
    try {
        Stream<String> stream = Files.lines(Paths.get(this.logFileName));
        List<LogMessage> sm = stream.filter(PATTERN_MAP.get(logLevel).asPredicate()).map(m -> {
            try {
                return objectMapper.readValue(m, LogMessage.class);
            } catch (IOException e) {
                logger.error("Parsing error");
                return null;
            }
        }).collect(Collectors.toList());
        return new ResponseEntity<>(sm, HttpStatus.OK);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        return new ResponseEntity<>(HttpStatus.EXPECTATION_FAILED);
    }

有两行示例数据在解析时失败:

{"level": "INFO", "timestamp": "2017-12-18T10:22:04.582","thread":"[Timer-0]", "loggername":" aspchina.service.ChoreographerSupportImpl.sendRequest(415)", "message": "RequestBody : {"action":{"actor":{"id":"FR2AR203","class":"unitOrConn"},"status":"stopped"}}"

使用上述数据不会创建任何对象。

0 个答案:

没有答案