0

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!

4
  • 1
    Recursive traversal of every node in the tree until you hit the property with the name "weWantThis" Commented Mar 6, 2018 at 19:14
  • @bhspencer How would I do that in a org.simple json though Commented Mar 6, 2018 at 19:16
  • Sorry im not very good Commented Mar 6, 2018 at 19:17
  • See if json-path is going to help you in this ? Commented Mar 6, 2018 at 19:29

3 Answers 3

0

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");
Sign up to request clarification or add additional context in comments.

10 Comments

Yes i've heard of that before. Very interesting.. never approached it because I never really understood it/didn't work. Any tips on how to implement that?
Added a concrete implementation
i get "java.lang.ClassCastException: net.minidev.json.JSONArray cannot be cast to java.base/java.lang.String" for some reason
Not sure. Are you using JSONPath or some other library.
Yes, JSONPath . is This correct though: I have a JSONObject called jsonResponse.. Can I then do String jsonResponseString = jsonResponse.toString(); then do Object document = Configuration.defaultConfiguration().addOptions(Option.SUPPRESS_EXCEPTIONS).jsonProvider() .parse(jsonResponseString );
|
0

You would first need to load this string into an JSONObject

Something like:

JSONObject ob = new JSONObject(string_content)

Now you need to go through each key,value pairs. The value can be either a simple object (Boolean, String, int etc) or a JSONArray or JSONObject. In both the later cases you can recursively call the same function you just wrote on the value only. In the case of JSONArray you will have to iterate over each item in the array and call this function recursively.

You keep on doing this until you find key is "weWantThis"

To find all keys in a given JSONObject you could use the whats suggested here: https://stackoverflow.com/a/20419508/2649309

https://www.codevoila.com/post/65/java-json-tutorial-and-example-json-java-orgjson#toc_5

How to parse JSON in Java

1 Comment

I'll give you the upvote if you write the recursive function :)
0

From the JSON string, simply do indexOf("\"weWantThis\": ") and then parse out the next value. Why run it through a JSON parser when you're only looking for a literal without structure?

2 Comments

This approach is probably more efficient than mine but will work until "weWantThis" exists only as a key. If this instance is present in a value field then, you will just have to be mindful about it and handle it gracefully.
@ArchitKhosla That's why I included the colon. Should only appear with the keys unless someone also has a colon in the values, which seems unlikely, but yes, you'd need to know the data to be certain.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.