fasterxml jackson objectmapper转换字符串

时间:2014-05-18 09:00:03

标签: java jackson json

我的字符串是:json = {“foo”:“bar”} {“foo”:“bar”}

========================

ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = null;
try { 
      final JsonParser jParser = mapper.getFactory().createParser(json);
      jsonNode = mapper.readTree(jParser);
  } catch (Exception e) {
      log.warn("Fail to parse the input json-string: ", e);
} 

=========================

杰克逊将其转换为:jsonNode = {“foo”:“bar”}

我想捕获此异常,但它在转换时不会抛出任何异常

1 个答案:

答案 0 :(得分:1)

您可能希望使用与答案中相同的技巧: How to detect trailing garbage using Jackson ObjectMapper

使用了mapper.readValue,但它应该与mapper.readTree类似。也就是说,在将JsonParser传递给映射器之后,检查jParser.nextToken()是否返回" null"。