在json中解析尾随字符 [英] trailing characters getting parsed in json
问题描述
我正在尝试检查json是否有效,并且遇到异常行为.
当我将某些字符附加到可解析的json时,杰克逊和gson都在解析它,并且它们忽略了结尾的字符.我想检查json是否严格有效.请帮忙.我在mapper.configure()
中尝试了几个标志,但是找不到确切的设置.
I am trying to check if json is valid and I am experiencing a bizzare behaviour.
When I append some characters to a parsable json both jackson and gson are parsing it and they ignore the trailing charaters. I want to check if the json is strictly valid. Please help. I tried a couple of flags in mapper.configure()
but I couldn't find the exact setting.
import com.google.gson.JsonParser;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
public class JSONUtil {
public static void main(String[] args) {
String jsonStr = "{\"outputValueSchemaFormat\": \"\",\"sortByIndexInRecord\": 0,\"sortOrder\":\"descending\"}opdfahf";
System.out.println(JSONUtil.isValidJson(jsonStr));
}
public static boolean isValidJson(String str) {
try {
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, true);
mapper.readTree(str);
System.out.println(str);
new JsonParser().parse(str);
} catch (Exception e) {
return false;
}
return true;
}
}
PS: This question is different from this because i have used the same code but it seems that either the library has some bug or some configuration flag is missing. I tried a couple of configuration flag but none seems to work.
推荐答案
在论坛上进行了一些研究之后,我发现了一个有趣的链接,其中有人遇到了同样的问题.团队的回应是
After some research on the forums i found an interesting link someone who had the same problem. The response from the team was
是的.这是设计使然.如果要解决此类问题,则需要构造JsonParser,并手动进行升级.存在多个根级别的值不认为是有效性问题,但是在您的情况下,将捕获不匹配']'的流末尾.
Yes. This is by design. If you want to catch such problems, you need to construct JsonParser, advance it manually. Existence of multiple root-level values is not considered a validity problem, but in your case, end-of-stream without matching ']' would be caught.
请在此处
有关解决方案,请此处
这篇关于在json中解析尾随字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!