syv
syv

Reputation: 3608

Processing Map with in Map values

For the below JSON

{
    "employee": {
        "insurances": {
            "insurance1": "45.1",
            "insurance2": "505.5"
        }
    },
    "id":61
}

Im using below code snippet to retrieve values from each field

Map<String, Object> insuranceDetails = (Map) ((Map) sourceAsMap.get("employee"))
    .get("insurances");

insuranceDetails.get("insurance1");
insuranceDetails.get("insurance2");

Would like to know is there any better/efficient way to achieve this? It has to run inside the loop so Im worrying about the performance. "insurance1" and "insurance2" are fixed fields.

Upvotes: 0

Views: 64

Answers (1)

Amin Heydari Alashti
Amin Heydari Alashti

Reputation: 1021

It's a better solution to create a entity class which it's properties are according to you json format.

class Json {
    long id;
    Map<String, Map<String, Float>> employee;
}

or even:

class Json {
    long id;
    Map<String, Insurrences> employee;
}

class Insurrences {
    Map<String, Float> insurrences;
}

class Converter {
    public static void main(String[] args) {
          String json = "{"employee":{"insurances”:{“insurance1”:”45.1","insurance2”:”505.5”}}, “id":61}";
          Gson gson = new Gson();
          Json jsonObj = gson.fromJson(json, Json.class);
          System.out.println(jsonObj.id);
    }
}

output would be: 61

gson librar: https://github.com/google/gson

Upvotes: 3

Related Questions