0

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.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
syv
  • 3,528
  • 7
  • 35
  • 50
  • Maybe try to parse it: https://stackoverflow.com/questions/2591098/how-to-parse-json-in-java – Bartek Sep 06 '18 at 11:48
  • 1
    Is it valid JSON? – Sumesh TG Sep 06 '18 at 11:48
  • 1
    Are you using any library for parsing JSON? What type is `sourceAsMap`? How is it build? Why should there be a *more efficient* way to do this using that library? It already looks straight and compact. – Zabuzard Sep 06 '18 at 11:53

1 Answers1

3

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