Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中通过hashMap读取json文件_Json - Fatal编程技术网

如何在java中通过hashMap读取json文件

如何在java中通过hashMap读取json文件,json,Json,我有一个非常简单的问题。我想通过java中的hashMap读取json文件 例如,我有一个json文件,如下所示: { "list": [ { "ID" : "#12354667", "value" : "data1." } { "ID" : "#12345789", "value" : "data2" } 每当我调用id时,它都会返回值。我写了这个,但我不知道如何阅读文件。有什么帮助吗 谢谢 private JsonReader()

我有一个非常简单的问题。我想通过java中的hashMap读取json文件

例如,我有一个json文件,如下所示:

{
    "list": [
       {
    "ID" : "#12354667",
    "value" : "data1."
}
   {
    "ID" : "#12345789",
    "value" : "data2"
}
每当我调用id时,它都会返回值。我写了这个,但我不知道如何阅读文件。有什么帮助吗

谢谢

private JsonReader() throws IOException {

    //readfile?
    this.messages = new HashMap<String, String>();
}

 public String getValue(final String ID)
    {
        if (this.messages.containsKey(ID))
        {
            return this.messages.get(value);
        }

        return "";
    }
您可以使用JSONParser和FileReader将文件读入应用程序。我不太确定这是否是您搜索的内容,但您可以尝试一下。你只需要给这个方法提供你的ID

JSONParser parser = new JSONParser();

    try {

        Object obj = parser.parse(new FileReader("c:\\yourFile.json"));

        JSONObject jsonObject = (JSONObject) obj;

        // loop array
        JSONArray list= (JSONArray) jsonObject.get("list");
        Iterator<String> iterator = list.iterator();

        while (iterator.hasNext()) {
           String id= (String) jsonObject.get("ID");
           if(id.equals(hereYourFinalString ID)){
              String value = (String) jsonObject.get("value");
              System.out.println(value);
           }
        }

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

     }