【问题标题】:How to process String of concatenated JSON blobs into List of Strings with Jackson?如何使用 Jackson 将连接的 JSON blob 字符串处理为字符串列表?
【发布时间】:2020-04-07 01:23:56
【问题描述】:

我有一个字符串,其中包含不同结构的连接 JSON 对象,我想将其转换为字符串列表。例如,给定这个输入:

{
  "foo": "bar"
}{
  "wibble": "wobble"
}

...我想要一个如下所示的List<String> 对象输出:

[{"foo":"bar"}, {"wibble":"wobble"}]

理想情况下,我想在不自己实现 JSON 规范的情况下做到这一点。如果我的初始字符串 not 包含额外的空格,我发现了一个使用 Jackson 的简单实现:

public List<String> extractJsonBlobs(String json) throws IOException {
    if (json.length() == 0) return ImmutableList.of();

    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode jsonNode = objectMapper.readValue(json, JsonNode.class);

    return new ImmutableList.Builder<String>()
            .add(jsonNode.toString())
            .addAll(extractJsonBlobs(
                    json.substring(jsonNode.toString().length())
            ))
            .build();
}
// this input works as described
String workingString = "{\"foo\":\"bar\"}{\"wibble\":\"wobble\"}";

// this input fails
String problemString = "{\n" +
        "  \"foo\": \"bar\"\n" +
        "}{\n" +
        "  \"wibble\": \"wobble\"\n" +
        "}";

问题是jsonNode.toString().length() 总是给我可能的最小表示(在这种情况下,第一个对象为 13),而我需要的是连接 JSON 对象的原始未处理字符串长度(第一个对象为 18)案子)。我怎样才能获得“原始”字符串长度 否则遍历这些 JSON 对象? 谢谢!

【问题讨论】:

  • 只需删除新行。
  • 不幸的是,问题不仅仅是换行符——任何额外的空格都会有同样的问题。
  • 然后也做一个 trim() 。否则,您需要将 json 解析为某个 Java 对象,然后将其解析回您认为合适的字符串。
  • trim() 消除了前导和尾随空格,但我还需要删除中间的空格。而且我无法删除 all 空格,因为字符串值中可能存在有效的空格。

标签: java json jackson


【解决方案1】:

我找到的解决方案涉及使用解析器(而不是仅使用 ObjectMapper 尝试此操作),而是使用 JsonNode 并再次依靠其 toString() 行为为我提供 JSON 字符串表示:

    public List<String> extractJsonBlobs(String json) throws IOException {
        JsonFactory factory = new JsonFactory(new ObjectMapper());
        JsonParser parser = factory.createParser(json);
        Iterator<JsonNode> messages = parser.readValuesAs(JsonNode.class);

        return Streams.stream(messages)
                .map(m -> m.toString())
                .collect(toList());
    }

【讨论】:

    猜你喜欢
    • 2021-05-11
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 2017-04-24
    相关资源
    最近更新 更多