Search code examples
javajsoneclipseparsingorg.json

JAVA Json automatic parsing for specific value


Note: This is org.json.simple

In the below examples, I always want the "weWantThis" value. For example, we have the Json:

Example1.

{
    "Header1": {
        "Basex": "ws",
        "Random": {
            "Something": "information"
        },
        "age": 22,
        "Type": "Apa",
        "correlation": "x",
        "weWantThis": "somethingHere"
    }
}

example 2.

{
    "Header1": {
        "useful": "yes",
        "code": 200,
        "creation": {
            "isValid": "yes",
            "date": 25,
            "items": [
                "pc"
            ],
            "weWantThis": "somethingHere"
        }
    }
}

So as you can see, the format of the Jsons is completely different, and could be even more different. The goal is to retrieve the value of "weWantThis", AUTOMATICALLY. i.e. all the other headers etc.. are unknown, other than "weWantThis" of course. If it is not even there, simply return null. So basically an automatic parsing needs to be done until "weWantThis" is found. No clue how to do this. Any help is appreciated. Thank you!


Solution

  • You can use the JSONPath library. It has support for wildcards and support for retrieving values of arbitrary keys by navigating through the json structure.

    JSONPath

    You can even try out your specific example here -

    Try out JSONPath

    Enter your desired JSON and then try this path -

    $..weWantThis
    

    Here is a concrete implementation -

    import com.jayway.jsonpath.Configuration;
    import com.jayway.jsonpath.JsonPath;
    import com.jayway.jsonpath.Option;
    import com.jayway.jsonpath.PathNotFoundException;
    
    Object document = Configuration.defaultConfiguration().addOptions(Option.SUPPRESS_EXCEPTIONS).jsonProvider()
                .parse(<jsonString>);
    String value = JsonPath.read(document, "$..weWantThis");