gpt4 book ai didi

java - 如何使用 java 8 迭代 JsonArray

转载 作者:行者123 更新时间:2023-11-30 02:03:24 26 4
gpt4 key购买 nike

我有如下 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中有没有办法避免代码重复。

最佳答案

您可以尝试使用内省(introspection)器或反射。并使用名称来查找属性或字段。内省(introspection)者:

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"));
}

反射(reflection):

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"));

}

关于java - 如何使用 java 8 迭代 JsonArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52076727/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com