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.