Populate jash hashmap with data from file

I have the following data structure:

"properties": {
    "P6": "head of government",
    "P7": "brother",
    "P9": "sister",
    "P10": "video",
    "P14": "highway marker",
    "P15": "road map",
    "P16": "highway system",
    "P17": "country",
    "P18": "image",
    "P19": "place of birth",
    "P20": "place of death",
    "P21": "sex or gender",


I would like to read this from a file and use it to populate a hashmap of the type Map<String,String>


I tried to do it with gson but was unsuccessful, I believe there should be an easier way.

Maybe I should read it and split into it using a pattern or regex?

This was the code I used:

         * P values file
        String jsonTxt_P = null;

        File P_Value_file = new File("properties-es.json");
        //raed in the P values
        if (P_Value_file.exists())
            InputStream is = new FileInputStream("properties-es.json");
            jsonTxt_P = IOUtils.toString(is);
        Gson json_P = new Gson();
        Map<String,String> massive_P_storage_map = new HashMap<String,String>();
        massive_P_storage_map = (Map<String,String>) json_P.fromJson(jsonTxt_P, massive_Q_storage_map.getClass());



source to share

1 answer

Do it like this

BufferedReader reader = new BufferedReader(new FileReader(new File("properties-es.json")));
        Map<String, HashMap<String, Object>> map = 
        new Gson().fromJson(reader, new TypeToken<HashMap<String, HashMap<String, Object>>>() {}.getType());


And here's how to get the value depending on the key name

String value = (String) map.get("properties").get("P6");




All Articles