2

I have a json object of objects and I'm trying to map the inner objects to a Java class.

{
"176294012937458694583": {
        "id": "176294012937458694583",
        "description": "Beta",
        "name": "BetaName",
        "account_id": "096382648647"
}
"3428378574582548573293": {
        "id": "3428378574582548573293",
        "description": "Omega",
        "name": "OmegaName",
        "account_id": "32735847382"
}
"4657556334646766874556": {
    "id": "4657556334646766874556",
    "description": "Delta",
    "name": "DeltaName",
    "account_id": "93758598257"
}
}

MyJavaClass 
String id;
String description;
String name;
String accountId;

I was hoping to access the inner objects like this & map to MyJavaClass using Gson:

JsonObject jsonObject = response.body().getAsJsonObject("176294012937458694583");
MyJavaClass myJavaClass = gson.fromJson(response.body().toString(), new TypeToken<MyJavaClass>(){}.getType());

But the inner objects' memberNames and number of inner objects are unknown until the json data returns. So what would be a better way to access and map these objects to MyJavaClass?

KoolKeith
  • 45
  • 4
  • To clarify, are the top-level keys (`"176294012937458694583"`, `"3428378574582548573293"`, and `"4657556334646766874556"`) unkown, but the keys in the nested objects (`"id"`, `"description"`, `"name"`, and `"account_id"`) all the same? – Code-Apprentice Apr 18 '23 at 20:19
  • 1
    you can convert to a `Map` where the key is this dynamic id: `Gson gson = new Gson(); Type type = new TypeToken>(){}.getType(); Map map = gson.fromJson(json, type);` after this, you can use `map.values()` and discard the keys – Emanuel Trandafir Apr 18 '23 at 22:01

2 Answers2

0

you can deserialise your string input as a map of string keys to MyJavaClass values objects using jackson's ObjectMapper :

var value = new ObjectMapper().readValue(inputString, new TypeReference<Map<String,MyJavaClass>>(){}););

You can then access your objects as follow :

value.get("176294012937458694583").getDescription();

rmk : for jackson to work properly you have to have a default constructor and explicit getters in MyJavaClass

Kurojin
  • 184
  • 6
0

As suggested by OldProgrammer, this answered my question. The custom serializer with jsonObject.entrySet to access my inner objects was what I needed to properly map to MyJavaClass.

KoolKeith
  • 45
  • 4