You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何验证完整JSON字符串是否已转换为Map集合

问题描述

需要验证下述方法中完整JSON字符串是否已转换为Map。当前示例里仅JSON字符串的第一部分被解析为Map,实际场景中JSON字符串为方法输入,且可能存在手动输入的空格;要求不使用DeserializationFeature.FAIL_ON_TRAILING_TOKENS,需在mapper.readValue后添加代码判断是否完成完整解析,并设置isParsed标记。

原方法代码:

public boolean isCompleteStringParsedInToJson() {
    boolean isParsed = false;
    String str = "{ \"tierkey 1\": \"Application\", \"tierkey 2\": \"Desktop\", \"tierkey 3\": \"Software\"}, { \"tierkey 4\": \"Application1\", \"tierkey 5\": \"Desktop2\", \"tierkey 6\": \"Software2\"}";
    ObjectMapper mapper = new ObjectMapper();
    
    try {
        Map map = mapper.readValue(str, Map.class);
        //check if complete input string is parsed into Map above. 
        // then set isParsed flag accordingly. 
        
    } catch (JsonProcessingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
    return isParsed;
}
解决方案

通过JsonParser追踪解析进度,检查解析后的剩余内容是否存在有效token(忽略空白字符),以此判断是否完成完整解析:

修改后的代码:

public boolean isCompleteStringParsedInToJson() {
    boolean isParsed = false;
    String str = "{ \"tierkey 1\": \"Application\", \"tierkey 2\": \"Desktop\", \"tierkey 3\": \"Software\"}, { \"tierkey 4\": \"Application1\", \"tierkey 5\": \"Desktop2\", \"tierkey 6\": \"Software2\"}";
    ObjectMapper mapper = new ObjectMapper();
    
    try {
        JsonParser parser = mapper.getFactory().createParser(str);
        // 解析JSON为Map
        Map map = mapper.readValue(parser, Map.class);
        
        // 将parser指针移到当前解析对象的末尾
        parser.skipChildren();
        // 跳过所有后续空白字符
        while (parser.nextToken() == JsonToken.WHITE_SPACE) {
            // 循环跳过空白,直到遇到有效token或结束
        }
        
        // 若没有剩余有效token,说明整个字符串已被完整解析
        if (parser.currentToken() == null) {
            isParsed = true;
        }
        
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    return isParsed;
}
关键说明
  • 用JsonParser绑定输入字符串,与ObjectMapper共享解析上下文,确保追踪的进度准确
  • skipChildren()方法确保解析完当前Map对应的JSON对象后,指针移动到对象的结束位置,避免遗漏子元素的判断
  • 手动跳过空白字符,过滤输入中可能存在的空格、换行等无效字符,保证判断的准确性
  • 最终通过检查是否还有剩余有效token,确认整个输入字符串是否被完整解析为Map

内容的提问来源于stack exchange,提问作者user5801655

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 04:50:43