我想解析這個JSON對象:
"{
\"Rao\":[\"Q7293658\",\"\",\"Q7293657\",\"Q12953055\",\"Q3531237\",\"Q4178159\",\"Q1138810\",\"Q579515\",\"Q3365064\",\"Q7293664\",\"Q1133815\"],
\"Hani Durzy\":[\"\"],
\"Louise\":[\"\",\"Q1660645\",\"Q130413\",\"Q3215140\",\"Q152779\",\"Q233203\",\"Q7871343\",\"Q232402\",\"Q82547\",\"Q286488\",\"Q156723\",\"Q3263649\",\"Q456386\",\"Q233192\",\"Q14714149\",\"Q12125864\",\"Q57669\",\"Q168667\",\"Q141410\",\"Q166028\"],
\"Reyna\":[\"Q7573462\",\"Q2892895\",\"Q363257\",\"Q151944\",\"Q3740321\",\"Q2857439\",\"Q1453358\",\"Q7319529\",\"Q733716\",\"Q16151941\",\"Q7159448\",\"Q5484172\",\"Q6074271\",\"Q1753185\",\"Q7319532\",\"Q5171205\",\"Q3183869\",\"Q1818527\",\"Q251862\",\"Q3840414\",\"Q5271282\",\"Q5606181\"]
}"
并使用該數(shù)據(jù)生成Map< String,HashSet< String>>.
基本上我想要逆轉(zhuǎn)this程序.
這個項目的所有代碼都可以在on my github page here找到,它很短.
更新
File f = new File("/home/matthias/Workbench/SUTD/nytimes_corpus/wdtk-parent/wdtk-examples/JSON_Output/user.json");
String jsonTxt = null;
if (f.exists())
{
InputStream is = new FileInputStream("/home/matthias/Workbench/SUTD/nytimes_corpus/wdtk-parent/wdtk-examples/JSON_Output/user.json");
jsonTxt = IOUtils.toString(is);
}
//System.out.println(jsonTxt);
Gson gson=new Gson();
Map<String, HashSet<String>> map = new HashMap<String, HashSet<String>>();
map=(Map<String, HashSet<String>>) gson.fromJson(jsonTxt, map.getClass());
//// \\ // ! PRINT IT ! // \\ // \\ // \\ // \\ // \\ // \ for (Map.Entry<String, HashSet<String>> entry : map.entrySet())
{
System.out.println(entry.getKey() " : " Arrays.deepToString(map.entrySet().toArray()) );
}
解決方法: 使用Gson
Gson gson = new Gson();
String json = "<YOUR_JSON_STRING_HERE>";
Map<String, HashSet<String>> map = new HashMap<String, HashSet<String>>();
map = (Map<String, HashSet<String>>) gson.fromJson(json, map.getClass());
更新:
使用TypeToken
Type type = new TypeToken<Map<String, HashSet<String>>>(){}.getType();
map = (Map<String, HashSet<String>>) gson.fromJson(json, type);
或者你可以解析它……
>創(chuàng)建一個JSONObject 的對象 >創(chuàng)建HashMap的對象 >迭代jsonObj.keys()并為每個鍵獲取值 jsonObj.getString(鍵). >將它放在map.put(key,value)中. 來源:http://www./content-1-198551.html
|