我是json的新手,我有很多谷歌,但无法找到解决方案。
这是我的json文件
{
"id": 1,
"firstname": "Katerina",
"languages": [
{
"lang": "en",
"knowledge": "proficient"
},
{
"lang": "fr",
"knowledge": "advanced"
}
]
}
我想获取语言数组的关键字和值,并按如下方式打印它们:
key is: lang and value is: en
key is: knowledge and value is: proficient
key is: lang and value is: fr
key is: knowledge and value is: advanced
我使用以下代码进行打印:
JSONParser parser = new JSONParser();
File file = new File("/Users/amzadhossain/Documents/jsonfile2.json");
FileReader reader = new FileReader(file);
JSONObject jsonObject = (JSONObject) parser.parse(reader);
JSONArray languages = (JSONArray) jsonObject.get("languages");
Map<String,String> map = new HashMap<String,String>();
List<Map<String, String>> lstmap = new ArrayList<Map<String, String>>();
Iterator<String> iter = null;
Iterator<String> iter2 = null;
for (int i =0; i<languages.size();i++){
JSONObject firstarr = (JSONObject) languages.get(i);
iter = firstarr.keySet().iterator();
iter2 = firstarr.values().iterator();
while(iter.hasNext()){
String key = (String)iter.next();
//String value = firstarr.toJSONString();
String value = (String)iter2.next();
map.put(key,value);
lstmap.add(i, map);
System.out.println(i+" ***** "+key + "#### " + map.get(key));
}
}
for(int i=0;i<lstmap.size();i++){
Map<String,String> mapget = lstmap.get(i);
for (Map.Entry<String, String> entry : mapget.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
但问题是它只打印最后一个键和值。请帮助。我想通过使用json simple来解决这个问题。
答案 0 :(得分:1)
检查以下代码。
final JSONParser parser = new JSONParser();
final File file = new File("/Users/amzadhossain/Documents/jsonfile2.json");
final FileReader reader = new FileReader(file);
final JSONObject jsonObject = (JSONObject) parser.parse(reader);
final JSONArray languages = (JSONArray) jsonObject.get("languages");
List<Map<String, String>> lstmap = new ArrayList<Map<String, String>>();
Iterator<String> iter = null;
for (int i = 0; i < languages.size(); i++) {
JSONObject firstarr = (JSONObject) languages.get(i);
iter = firstarr.keySet().iterator();
while(iter.hasNext()){
final Map<String, String> map = new HashMap<String, String>();
String key = (String)iter.next();
Object value = firstarr.get(key);
map.put(key, value.toString());
lstmap.add(map);
System.out.println("key is "+key + " and value is " + value);
}
}
for (Map<String, String> map : lstmap){
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
答案 1 :(得分:0)
这可能对您有帮助,
for(int i =0; i<languages.length();i++){
lstmap = new ArrayList<Map<String, Object>>();
JSONObject firstarr = (JSONObject) languages.get(i);
iter = firstarr.keySet().iterator();
while(iter.hasNext()){
String key = (String)iter.next();
Object value = firstarr.get(key);
System.out.println("key is "+key + "and value is " + value);
}
}