skip to Main Content

I want to check if complete JSON string gets converted to Map in below method.

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;
}

In above case, only "{ "tierkey 1": "Application", "tierkey 2": "Desktop", "tierkey 3": "Software"}" part is returned as Map. In actual scenario JSON String will be input to the method. In above method I just need to identify cases where complete JSON string is parsed into Map or not and then accordingly set isParsed flag value(true or false).
JSON String mentioned in the method is not strict JSON and readValue don’t fail for such JSON string. Also dont want to use DeserializationFeature.FAIL_ON_TRAILING_TOKENS on ObjectMapper.
Input JSON string can be manually written so there could be few spaces before key or Value.

What code I should have after mapper.readValue to check complete JSON string parsing into Map?

2

Answers


  1. if the readValue() line does not throw an exception, that means the parsing was successful and you can set your flag to true. in the "catch" block, set your flag to false.

    Login or Signup to reply.
  2. The problem is that your string contains 2 separate JSONs.

    {"tierkey 1 : "Application", "tierkey 2": "Desktop", "tierkey 3": "Software"}, { "tierkey 4": "Application1", "tierkey 5": "Desktop2", "tierkey 6": "Software2"}
    

    Note that after key "tierkey 3" there is a ‘}’ which closes the first opening ‘{‘. So when Json is parsed and it reaches the end of it it Ignores whaterver comes after. so your part from ", { "tierkey 4": "Application1",...}" is ignored and it is correct behavior. If you want it to be parsed modify your string to

    {"tierkey 1 : "Application", "tierkey 2": "Desktop", "tierkey 3": "Software",  "tierkey 4": "Application1", "tierkey 5": "Desktop2", "tierkey 6": "Software2"}
    

    or

    {{"tierkey 1 : "Application", "tierkey 2": "Desktop", "tierkey 3": "Software"}, { "tierkey 4": "Application1", "tierkey 5": "Desktop2", "tierkey 6": "Software2"}}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search