首页 > 解决方案 > 使用地图值处理地图

问题描述

对于下面的 JSON

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

我使用下面的代码片段从每个字段中检索值

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

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

想知道有没有更好/有效的方法来实现这一目标?它必须在循环内运行,所以我担心性能。“insurance1”和“insurance2”是固定字段。

标签: javajson

解决方案


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


推荐阅读