0

I am searching a good and dynamic way to parse JSON in Java. I've seen things such as:

List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("test");
for(int i = 0 ; i < array.length() ; i++){
    list.add(array.getJSONObject(i).getString("testKey"));
}

But that's not what I'm searching. In C# I had something like that:

dynamic results = JsonConvert.DeserializeObject<dynamic>(json); 
info.Text = results["test"]["testKey"];

Here's an example of my JSON:

{"date":"07.05.2017 11:44",
"monday":{"1":{"subject":"test","room":"test","status":"test"}}}

So for example I would like to make:

results["monday"]["1"]["subject"];

I hope someone understands my problem and can help me. Thanks in advance!

3
  • What don't you like about the first example in your post? Commented May 7, 2017 at 9:56
  • @ItamarGreen because I have to add every single key/object and that's really annoying.. I just want a dynamic way to get this JSON-Keys like in C# or PHP. Commented May 7, 2017 at 10:00
  • There are many Json parsers out there for Java. Each has its own capabilities. But Java is not C#, and you can't have array indices which are strings. Anyway, you are comparing oranges and apples - in your Java example, you were parsing a Json Array, and in the C# example, you were parsing a Json Object. Commented May 7, 2017 at 10:13

3 Answers 3

1

The core Java runtime does not offer a JSON parser (edit: technically, it does, see bottom of answer), so you will need a library. See Jackson, Gson, perhaps others.

Even with that, you will not get the dynamic features you want, because Java is statically typed. Example with Jackson:

    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue(json, new TypeReference<Map<String, Object>>(){});

    map.get("monday").get("1").get("subject");
                      ^^^
                      This fails because the result of get("monday") is Object, not Map

The "right" approach in Java-land, would be to create a class (or set of classes) that represents your JSON model, and pass it to the JSON parser's "object mapper". But you said "dynamic" so I'm not exploring this here. So you'll need to cast to Map when you know it's not primitive values: ((Map<String,Map<String,String>>)map.get("monday")).get("1").get("subject");

This works but with a warning about unchecked cast...

All in all, Java is not a dynamic language and I see no way to do exactly what you want (perhaps I'm missing approaches that are still slightly easier than what I have suggested).

Are you limited to Java-the-language or Java-the-platform? In the latter case you can use a dynamic language for the Java platform, such as Groovy, who has excellent features to parse JSON.

EDIT: a funny alternative is to use Java's own JavaScript implementation. This works and is easy and dynamic, but I don't know if it's "good":

    String json = "{\"date\":\"07.05.2017 11:44\",\n" +
            "\"monday\":{\"1\":{\"subject\":\"test\",\"room\":\"test\",\"status\":\"test\"}}}";
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    engine.put("data", json);
    System.out.println(engine.eval("JSON.parse(data)['monday']['1']['subject']"));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! ((Map<String,Map<String,String>>)map.get("monday")).get(i).get("subject") is working good. Exactly what I wanted. :)
1

If you are sure about the value you want to get then you can do following as well :

String str = "{\"date\":\"07.05.2017 11:44\", \"monday\":{\"1\":{\"subject\":\"test\",\"room\":\"test\",\"status\":\"test\"}}}";
JSONObject results= new JSONObject(str);
String str1 = results.getJSONObject("monday").getJSONObject("1").getString("subject");
System.out.println(str1);

For array kind of results, we have to write logic for that. In this case org.json library is used.

2 Comments

Ah, nice, I missed that one, it's probably dynamic-enough. The library is called "GSON" though.
GSON is another library for JSON parsing, which I have used is different one.
0

You can use GCON library: https://github.com/google/gson

Very good for parsing JSON objects.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.