Skip to content
Advertisement

Check if JSON is valid in JAVA using Jackson

I have a JSON string which I am storing it in DB as a string. In front-end, I am rendering this JSON as object.

I am using:

JSON.parse(string);  
Uncaught Syntax error: Unexpected Token  

String :

{
"id": "295cd59f-4033-438c-9bf4-c571829f134e",
"from": "Shrisha S.<shrisha@s.com>",
"to": [
    "Katie Porter <katie.porter@ss.com>"
],
"cc": [
    "Jack d<jack.d@dd.com>,     Keerthi<keerthi.s@dd.com>"
],
"bcc": [

 ]  
}

Is there any way I can check If JSON is valid or not in JAVA?

One thing to be noted here is that, I don’t have a schema defined for JSON which I can map to, i.e. JSON can hold anything.

I am currently trying out with JACKSON but for that I need a pre-defined schema which I don’t have. Is there anyway this can be fixed?

Advertisement

Answer

You can read it as a JsonNode, no need to map it to a specific Class, its generic:

try{

  ObjectMapper objectMapper = ...;
  JsonNode jsonNode = objectMapper.readTree(yourJsonString);

} catch(JsonProcessingException e){........}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement