简体   繁体   中英

How to check if complete JSON string is converted into Map

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM