-2

I am using a public API that gives me a list of Objects but they not in a ArrayList as below:

FYI this is just a portion of the JSON Response.

FYI 2: This is already being parsed using Gson from Retrofit

"dataCenters": {
        "Peru": {
            "capacity": "full",
            "load": "idle"
        },
        "EU West": {
            "capacity": "full",
            "load": "low"
        }
  }

As you can see the dataCenters object is not a list. How would I be able to add this list of objects to an arraylist?

I have made all the dataCenters the same type of object called DataCentersStatus so that i dont have a long list of different models that all are basically the same just have different names.

Thank you

Stillie
  • 2,647
  • 6
  • 28
  • 50

1 Answers1

1

You can do that using gson.

    JsonParser parser = new JsonParser();
    JsonElement element = parser.parse(jsonAsString);
    JsonElement dataCenters = element.getAsJsonObject().get("dataCenters");
    Set<Map.Entry<String, JsonElement>> entries = dataCenters.getAsJsonObject().entrySet();
    List<DataCenter> list = new LinkedList<>();
    Gson gson = new Gson();
    for (Map.Entry<String, JsonElement> entry: entries) {
        DataCenter dc = gson.fromJson(entry.getValue(), DataCenter.class); 
        dc.setName(entry.getKey());
        list.add(dc);
    }

DataCenter is a class with fields name, capacity and load.

More information you can find here.

Maven dependency

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.1</version>
</dependency>
wpater
  • 393
  • 3
  • 14