首页 > 解决方案 > 如何使用 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 中有什么办法可以避免代码重复。

标签: javaarraysjsoniterator

解决方案


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

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

}

推荐阅读