【发布时间】:2019-02-04 04:48:36
【问题描述】:
我有如下的 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中有什么方法可以避免代码重复。
【问题讨论】:
-
可以使用switch语句
-
这里好像已经回答了这个问题,请检查。 stackoverflow.com/questions/42854505/…
-
你好。我不确定是否有替代方案。这是你的数据结构的结果。
-
为什么需要
name和value键?在我看来,它们是多余的。例如,您可以拥有"customerGroupId" : ""等。通过这种方式,您可以直接分配给正确的属性,因为您知道将从 json 中获得哪个属性。 -
想到了这一点,但对后端 Json 无能为力