如何使用Java 8迭代JsonArray

时间:2018-08-29 11:48:37

标签: java arrays json iterator

我的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中有什么方法可以避免重复代码。

1 个答案:

答案 0 :(得分:2)

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

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

}