在Java中使用未知密钥解析JSON对象

时间:2018-05-14 09:19:37

标签: java json parsing

我正在制作一个小程序,将可用的拼字游戏字母与字典中的单词匹配。我发现a neat JSON file包含了英语中的大多数单词,现在我想解析它并为其中的每个单词创建一个Word对象(带有名称和定义值)。格式与我以前使用的JSON文件完全不同,我不知道如何继续。对于每个单词,单词本身是关键,定义是值。我希望以一种既能给我关键又能给我价值的方式解析它,这样我就可以用它来制作一个新的Word对象。

这里是json文件的格式(非常简短,只是为了给你一般的要点。

{"DIPLOBLASTIC":"Characterizing the ovum when it has two primary germinallayers.","DEFIGURE":"To delineate. [Obs.]These two stones as they are here defigured. Weever.","LOMBARD":"Of or pertaining to Lombardy, or the inhabitants of Lombardy."}

最有效的方法是什么?

1 个答案:

答案 0 :(得分:1)

public static void main(String[] args) {
        final String json = "{\"DIPLOBLASTIC\":\"Characterizing the ovum when it has two primary germinallayers.\",\"DEFIGURE\":\"To delineate. [Obs.]These two stones as they are here defigured. Weever.\",\"LOMBARD\":\"Of or pertaining to Lombardy, or the inhabitants of Lombardy.\"}";

        ObjectMapper mapper = new ObjectMapper();
        try {
            HashMap<String,String> map = mapper.readValue(json, HashMap.class);
            for(Map.Entry e : map.entrySet()){
                System.out.println(e.getKey() + ":" + e.getValue());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

输出

DEFIGURE:To delineate. [Obs.]These two stones as they are here defigured. Weever.
DIPLOBLASTIC:Characterizing the ovum when it has two primary germinallayers.
LOMBARD:Of or pertaining to Lombardy, or the inhabitants of Lombardy.