java - 如何使用 java 8 迭代 JsonArray
问题描述
我有如下的 Json 数组
{ "template": { "data": [{ "name": "customerGroupId", "value": "" }, { "name": "assetIntegrationId", "value": "" }, { "name": "problemCategory", "value": "" }, { "name": "problemSubCategory", "value": "" }, { "name": "resolutionCode", "value": "" }, { "name": "resolutionSubCode", "value": "" }, { "name": "imei", "value": "" }, { "name": "make", "value": "" }, { "name": "model", "value": "" }] } }
我正在使用以下代码来获取值。
JSONArray jsonArray = jsonObject.getJSONObject("template").getJSONArray("data");
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObjectData = jsonArray.getJSONObject(i);
if ("customerGroupId".equals(jsonObjectData.get("name"))) {
customerBean.setCustomerGroupId(jsonObjectData.get(VALUE).toString());
LOGGER.debug("JSON customerGroupId " + jsonObjectData.get(VALUE).toString());
} else if ("assetIntegrationId".equals(jsonObjectData.get("name"))) {
customerBean.setAssetIntegrationId(jsonObjectData.get(VALUE).toString());
LOGGER.debug("JSON assetIntegrationId " + jsonObjectData.get(VALUE).toString());
} else if ("problemCategory".equals(jsonObjectData.get("name"))) {
customerBean.setProblemCategory(jsonObjectData.get(VALUE).toString());
LOGGER.debug("JSON problemCategory " + jsonObjectData.get(VALUE).toString());
} else if ("problemSubCategory".equals(jsonObjectData.get("name"))) {
customerBean.setProblemSubCategory(jsonObjectData.get(VALUE).toString());
LOGGER.debug("JSON problemSubCategory " + jsonObjectData.get(VALUE).toString());
} else if ("resolutionCode".equals(jsonObjectData.get("name"))) {
customerBean.setResolutionCode(jsonObjectData.get(VALUE).toString());
LOGGER.debug("JSON resolutionCode " + jsonObjectData.get(VALUE).toString());
}
由于代码已经变得重复,Java 8 或 Java 中有什么办法可以避免代码重复。
解决方案
您可以尝试使用内省或反射。并使用名称查找属性或字段。内省者:
JSONArray json = new JSONArray();
CustomerBean customerBean = new CustomerBean();
for (int i = json.size() - 1; i >= 0; i--) {
JSONObject data = json.getJSONObject(i);
PropertyDescriptor propDesc = new PropertyDescriptor(data.getString("name"), CustomerBean.class);
Method methodWriter = propDesc.getWriteMethod();
methodWriter.invoke(customerBean, data.getString("value"));
}
反射:
JSONArray json = new JSONArray();
CustomerBean customerBean = new CustomerBean();
for (int i = json.size() - 1; i >= 0; i--) {
JSONObject data = json.getJSONObject(i);
Field field = CustomerBean.class.getDeclaredField(data.getString("name"));
field.set(customerBean, data.get("data"));
}
推荐阅读
- python - 具有一些固定值的向量作为 scipy 最小化函数的变量
- python-3.x - Python 包装器导致冗余函数调用
- javascript - 如何使用 CSS 个性化谷歌地图上的标记
- java - Java JDBC SQL Server 2017 连接时间过长
- spring-boot - 使用 Springboot 通过 CassandraConfig 获取指标异常
- go - 尝试了解如何从 int params 构建数组
- r - 为什么 renderUI 不呈现输入链中的 selectInput
- tpm - 使用 TPM / TrouSerS API 创建密钥时出现“身份验证失败”
- angular - 最后一列的primeng过滤器位置
- python - 如何输入碰撞?