java - 使用地图值处理地图
问题描述
对于下面的 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”是固定字段。
解决方案
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
推荐阅读
- python - 如何优化熊猫中的数据框迭代?
- python - numpy.core._exceptions.MemoryError:无法为形状为 (1073741824, 0) 且数据类型为 float32 的数组分配 0 个字节
- go - 从 Go 中的无效字符串“24-Sep.-20”解析时间
- informatica - 我必须将以下 SQL 查询转换为 informatica 云逻辑
- python - Dash plotly - 如何在回调中包含跟踪标记样式而不导致无法使用的延迟?
- java - 我将如何为这款 Red Black Tree 插件执行对称案例?
- r - 交互作用中的生存分析参考
- javascript - facebook 图像 url 到 blob 数据
- ruby-on-rails - 如何测试是否在使用 RSpec 从 Rails 中的数据库中提取的特定对象上调用方法?
- javascript - 除了 App.js 之外没有代码的全新项目:错误:无效的钩子调用。Hooks 只能在函数组件的主体内部调用