鉴于Json,我只得到第一个数组的值(例如,我只得到一个值" timestamp"),下面的代码如下。
[
{
"type": "Brand",
"matchedProducts": [],
"matchedIds": [
"adidas",
"adidas"
],
"timestamp": 1440961761478
},
{
"type": "Category",
"matchedProducts": [
1543669767
],
"matchedIds": [],
"timestamp": 1440962000467
}
]
当我将上面的Json字符串作为s和key传递给timestamp然后我只获得一个时间戳时,这是方法。我想要两个。有人可以帮我。
public static List<String> getValuesAsListFromJson2Lvl(String s, String key) throws ParseException, JSONException {
JSONParser parser = new JSONParser();
String name = null;
JSONObject obj;
s = s.substring(s.indexOf("[")+1);
s = s.substring(0,s.lastIndexOf("]"));
Logger.log("s:"+ s);
obj = new JSONObject(s);
List<String> values = new ArrayList<String>();
String valuesAsString = null;
Logger.log("obj.toString():"+ obj.toString());
if ("matchedIds".equalsIgnoreCase(key)) {
JSONArray jsonArray = obj.getJSONArray(key);
Logger.log("jsonArray.length() for key is:" + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
Logger.log("jsonArray.get(" + i + ")" + jsonArray.get(i));
values.add((String) jsonArray.get(i));
}
} else if ("timestamp".equalsIgnoreCase(key)) {
String tmp = obj.getString(key);
Logger.log("tmp:" + tmp);
JSONObject jsonObject = obj.getJSONObject(key);
Logger.log("jsonObject.get(" + key + ") :" + jsonObject.get(key));
values.add((String) jsonObject.get(key));
}
return values;
}
}
答案 0 :(得分:1)
使用以下代码返回正确答案:
public static List<String> getValuesAsListFromJson2Lvl(String s, String key) throws JSONException {
JSONArray jsonArray = new JSONArray(s);
List<String> values = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String value = jsonObject.get(key).toString();
values.add(value);
}
return values;
}