在我的项目中,有这样一个JSON文件:
{
"table1": [],
"table2": [{
"field1": "value1",
"field2": "value2",
"field3": "value3"
}],
"table3": []
}我通过JSON将其传输到一个JSONObject。有一种方法可以获得我已经编码的子节点,如下所示:
public static JSONObject getChildNode(JSONObject json, String nodeName,
String fieldName1,Object filedValue1, String fieldName2,Object filedValue2) {
JSONArray jsonArray = (JSONArray) json.get(nodeName);
JSONObject jsonObject = null;
for (int i = 0; i < jsonArray.size(); i++) {
jsonObject = (JSONObject) jsonArray.get(i);
String value1 = (String) jsonObject.get(fieldName1);
String value2 = (String) jsonObject.get(fieldName2);
if (value1.equals(filedValue1) && value2.equals(filedValue2)) {
return jsonObject;
}
}
return null;
}现在我想使用一个映射来存储参数,键是fieldName,值是字段的值,如下所示:
public JSONObject getChildNode(JSONObject json, String nodeName, Map<String, Object> map) {}问题是:我不知道它将传递多少参数,但是Map的每个值都需要等于jsonArray的值。最后返回我需要的JSONObject。
有人能帮我吗?非常感谢。
我编写了如下代码:
public JSONObject getChildNode(JSONObject json, String nodeName, Map<String, Object> map) {
JSONArray jsonArray = (JSONArray) json.get(nodeName);
JSONObject jsonObject,jsonObjectTmp = null;
for(int i=0; i<jsonArray.size(); i++) {
jsonObject = (JSONObject) jsonArray.get(i);
for (String key : map.keySet()) {
String jsonKey = (String) jsonObject.get(key);
if (jsonKey.equals(map.get(key))){
jsonObjectTmp = jsonObject;
}else {
jsonObjectTmp = null;
break;
}
}
}
return jsonObjectTmp;
}但我不知道我该把JSONObject还给哪里?
添加代码:
public JSONObject getChildNode(JSONObject json, String nodeName, Map<String, Object> map) {
JSONArray jsonArray = (JSONArray) json.get(nodeName);
JSONObject jsonObject = null;
boolean flag;
for(int i=0; i<jsonArray.size(); i++) {
jsonObject = (JSONObject) jsonArray.get(i);
flag = mapsAreEqual(jsonObject, map);
if (flag) {
return jsonObject;
}
}
return null;
}
public static boolean mapsAreEqual(Map<String, Object> mapA, Map<String, Object> mapB) {
try{
for (String k : mapB.keySet())
{
if (mapA.get(k).hashCode() != mapB.get(k).hashCode()) {
return false;
}
}
} catch (NullPointerException np) {
return false;
}
return true;
}发布于 2015-08-19 19:05:48
只需像前面提到的那样,将参数映射传递给getChildNodeMethod:
public JSONObject getChildNode(JSONObject json, String nodeName, Map<String, Object> map) {}然后,在第一步中,循环遍历json数组(就像您已经做的那样),并将条目写入另一个映射中。在第二步中,您将比较这两幅地图。如果不打算比较键值对的顺序,请确保不进行比较。
下面是关于如何比较两幅地图的另一个问题:Comparing two hashmaps for equal values and same key sets?
https://stackoverflow.com/questions/32103300
复制相似问题