用Java解析JSON对象我有JSON对象,如下所示:member = "{interests : [{interestKey:Dogs}, {interestKey:Cats}]}";在Java中,我希望解析上面的json对象,并将这些值存储在数组中。我正在寻找一些代码,通过它我可以实现这一点。
3 回答
繁花不似锦
TA贡献1851条经验 获得超4个赞
JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");List<String> list = new ArrayList<String>();JSONArray array = obj.getJSONArray("interests");for(int i = 0 ; i < array.length() ; i++){ list.add(array.getJSONObject(i).getString("interestKey"));}
四季花海
TA贡献1811条经验 获得超5个赞
public class JsonParsing {public static Properties properties = null;public static JSONObject jsonObject = null;static { properties = new Properties();}public static void main(String[] args) { try { JSONParser jsonParser = new JSONParser(); File file = new File("src/main/java/read.json"); Object object = jsonParser.parse(new FileReader(file)); jsonObject = (JSONObject) object; parseJson(jsonObject); } catch (Exception ex) { ex.printStackTrace(); }}public static void getArray(Object object2) throws ParseException { JSONArray jsonArr = (JSONArray) object2; for (int k = 0; k < jsonArr.size(); k++) { if (jsonArr.get(k) instanceof JSONObject) { parseJson((JSONObject) jsonArr.get(k)); } else { System.out.println(jsonArr.get(k)); } }}public static void parseJson(JSONObject jsonObject) throws ParseException { Set<Object> set = jsonObject.keySet(); Iterator<Object> iterator = set.iterator(); while (iterator.hasNext()) { Object obj = iterator.next(); if (jsonObject.get(obj) instanceof JSONArray) { System.out.println(obj.toString()); getArray(jsonObject.get(obj)); } else { if (jsonObject.get(obj) instanceof JSONObject) { parseJson((JSONObject) jsonObject.get(obj)); } else { System.out.println(obj.toString() + "\t" + jsonObject.get(obj)); } } }}}
添加回答
举报
0/150
提交
取消