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!

user6671584
  • 45
  • 1
  • 8

3 Answers3

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

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?

Thom
  • 14,013
  • 25
  • 105
  • 185
  • 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. – Archit Khosla Mar 06 '18 at 20:02
  • @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. – Thom Mar 06 '18 at 20:03
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");
Sashi
  • 1,977
  • 16
  • 15
  • 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? – user6671584 Mar 06 '18 at 20:28
  • Added a concrete implementation – Sashi Mar 06 '18 at 20:34
  • i get "java.lang.ClassCastException: net.minidev.json.JSONArray cannot be cast to java.base/java.lang.String" for some reason – user6671584 Mar 06 '18 at 20:51
  • Not sure. Are you using JSONPath or some other library. – Sashi Mar 06 '18 at 21:00
  • 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 ); – user6671584 Mar 06 '18 at 21:18
  • Or am I doing something stupidly wrong here – user6671584 Mar 06 '18 at 21:18
  • Not sure how you constructed your JSONObject. You could probably do JSONObject.toJSONString() to get the json string. – Sashi Mar 06 '18 at 21:23
  • Yes I tried both .toString and .toJSONString and both give the same error. And it looks just like the examples in the question – user6671584 Mar 06 '18 at 21:25
  • Got it. Just had to do a .toString after, i.e.: String value = JsonPath.read(document, "$..weWantThis").toString(); – user6671584 Mar 06 '18 at 21:44
  • Glad it worked out. – Sashi Mar 06 '18 at 21:46