Home > Mobile >  Object containing a JSON array won't parse into a JSONArray Object Java (org.json.simple)
Object containing a JSON array won't parse into a JSONArray Object Java (org.json.simple)

Time:03-09

I've been trying to access a JSON array bedded in a JSONObject (org.json.simple) to get the values or just the size of the array.

This is a simplified version of the JSON provided:

{
    "paymentId" : 123,
    "creditors" : [
        {
            "id" : 1,
            "name" : "name1"
        },
        {
            "id" : 2,
            "name" : "name2"
        }
    ]
}

In my current attempt the JSON data is stored in a JSONObject (org.json.simple) and I am trying to get the size of the "creditors"-array and the names of the creditors. Here is what I've got so far:

public String getNumberOfTransactions(JSONObject inputData){
    int numberOfTransactions = 0;
    if(inputData.containsKey("creditors")){
        System.out.println("inputData contains key");
        Object simpleCreditorsObject = inputData.get("creditors");
        if(simpleCreditorsObject instanceof JSONArray) {
            System.out.println("worked");
        }
    }
    return Integer.toString(numberOfTransactions);
}

The console logs show, that the inputData contains the key.

When console logging the simpleCreditorsObject it prints:

{"creditors":[{"id":1,"name":"name1"},{"id":2,"name":"name2"}],"paymentId":123}

When I try to just parse it:

JSONArray creditors = (JSONArray) simpleCreditorsObject;

This exception shows:

class java.util.ArrayList cannot be cast to class org.json.simple.JSONArray (java.util.ArrayList is in module java.base of loader 'bootstrap'; org.json.simple.JSONArray is in unnamed module of loader 'app')

It seems like the Object isn't instanceOf JSONArray but i can't get why. Is it a totally wrong attempt or am I missing a part?

CodePudding user response:

Well, you can easily diagnose the problem by replacing

if(simpleCreditorsObject instanceof JSONArray) {
    System.out.println("worked");
}

with:

if(simpleCreditorsObject instanceof JSONArray) {
    System.out.println("worked");
} else {
    System.out.println("class: "   simpleCreditorsObject.getClass().getName());
}

But I suggest to switch from json.simple library to Jackson JSON library. See those links: Jackson JSON Tutorial, Jackson on github and Maven repositories. Also, just to simplify your task you can use Another open source library that provides a simple wrapper over Jackson JSON library. in this case your code may look like this (assuming that you your input String param contains your JSON String:

{ "paymentId" : 123, "creditors" : [ { "id" : 1, "name" : "name1" }, { "id" : 2, "name" : "name2" } ] }

the method may look as folows:

public void parseJson(String input) {
  try {
    Map<String, Object> myMap = JsonUtils.readObjectFromJsonString(input, Map<String, Object>.class);
    List<Map<String, Object>> creditors = (List<>)myMap.get("creditors");
    System.out.println("Number of creditors: "   creditors.size());
    System.out.println("Creditor names:");
    for(Map<String, Object>> map : creditors) {
      System.out.println(map.get("name"));
    }
  } catch(Exception e) {
    e.printStacktrace();
  }
}

Here is the JavaDoc for the JsonUtils class. The library could be found as Maven artifact and on Github (including source code and Javadoc).

  • Related