如何将JSON对象解析为“Map<String,HashSet<String>>”

5

我想解析这个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\"]
}"

并使用这些数据生成一个Map<String,HashSet<String>>。实质上,我想要反转过程。您可以在我的GitHub页面找到此项目的所有代码,它非常简短。


更新

        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()) );
       }

展示你的Java代码。 - Scary Wombat
1个回答

6
使用 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());

更新:
使用
Type type = new TypeToken<Map<String, HashSet<String>>>(){}.getType();
map = (Map<String, HashSet<String>>) gson.fromJson(json, type);

或者你可以解析它...

  • 创建一个 JSONObject 对象
  • 创建一个 HashMap 对象
  • 遍历 jsonObj.keys(),并且对于每个 key 获取 value,例如 jsonObj.getString(key)
  • 将其放入 map 中,例如 map.put(key, value)

什么是JSON字符串?我可以使用BufferedReader读取文件并生成JSON字符串吗?我以前从未做过这个,请原谅我。 - smatthewenglish
@S.Matthew_English 是的。 - ComputerFellow
也许类似于这个:https://dev59.com/l2kw5IYBdhLWcg3w2-TH - smatthewenglish
我的IDE给了我大约20个要导入的选项,但我无法确定哪一个是“Type”?这与“gson”有关吗? - smatthewenglish
@S.Matthew_English 是的,它来自gson http://google-gson.googlecode.com/svn/tags/1.1/docs/javadocs/com/google/gson/reflect/TypeToken.html - ComputerFellow
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接