0

I need to save this hashmap in SharedPreferences i tried to convert it into Json but it didn't work

 Map<String, String> userMap = new HashMap<String , String>() {{
                for(int i = 0; i < userList.size(); i++ ) {
                    String id= userList.get(i).getId();
                    String name = userList.get(i).getName();
                    put(id, name);

                }
            }};
            Gson gson = new Gson();
            String jsonString = gson.toJson(userMap);
            SessionManager sessionManager=new SessionManager(LoginActivity.this);
            sessionManager.saveMap(jsonString); 

jsonString is returing null even usermap has data I really need this to advance in my work appreciate anyhelp.

1 Answers1

0

Gson is not recognizing the anonymous class that results from doing it that way.

Try initializing the map without using the {{}} construct. e.g.

Map<String, String> userMap = new HashMap<String , String>();

for(int i = 0; i < userList.size(); i++ ) {
    String id= userList.get(i).getId();
    String name = userList.get(i).getName();
    put(id, name);
}

Gson gson = new Gson();
String jsonString = gson.toJson(userMap);
SessionManager sessionManager=new SessionManager(LoginActivity.this);
sessionManager.saveMap(jsonString); 

To convert this json back to a Map<String, String> you can use TypeToken as suggested here.

Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>() {}.getType();
Map<String, String> nameEmployeeMap = gson.fromJson(jsonString, type);
avd
  • 174
  • 2
  • 8
  • Thank you bro it works but do you have an idea after i retrieve the json string how can i convert it back to hashmap – Mohamed Aziz Ben haj laroussi Sep 29 '21 at 23:34
  • Yes, you have to use `TypeToken` to get it back in a type-safe way. Heads up, if the underlying json does not comply with this type token, it will raise an exception. I guess in your case it will always do. – avd Sep 30 '21 at 00:07