How to read and write a HashMap to a file?

前端 未结 5 428
南笙
南笙 2020-12-09 04:13

I have the following HashMap:

HashMap fileObj = new HashMap();

ArrayList cols         


        
5条回答
  •  执笔经年
    2020-12-09 04:37

    you can also use JSON file to read and write MAP object.

    To write map object into JSON file

        ObjectMapper mapper = new ObjectMapper();
    
        Map map = new HashMap();
        map.put("name", "Suson");
        map.put("age", 26);
    
        // write JSON to a file
        mapper.writeValue(new File("c:\\myData.json"), map);
    

    To read map object from JSON file

        ObjectMapper mapper = new ObjectMapper();
    
            // read JSON from a file
            Map map = mapper.readValue(
                    new File("c:\\myData.json"),
                    new TypeReference>() {
            });
    
            System.out.println(map.get("name"));
            System.out.println(map.get("age"));
    

    and import ObjectMapper from com.fasterxml.jackson and put code in try catch block

提交回复
热议问题