【发布时间】:2016-12-17 20:21:30
【问题描述】:
我正在尝试检查 json 是否有效并且我遇到了奇怪的行为。
当我将一些字符附加到可解析的 json 时,jackson 和 gson 都在解析它,它们忽略了尾随字符。我想检查 json 是否严格有效。请帮忙。我在mapper.configure() 中尝试了几个标志,但找不到确切的设置。
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 不同,因为我使用了相同的代码,但似乎库有一些错误或缺少一些配置标志。我尝试了几个配置标志,但似乎都不起作用。
【问题讨论】: