Menu

sereializing and deserializing a hashmap

Help
2015-10-02
2015-10-03
  • danny sarge

    danny sarge - 2015-10-02

    Hey, I've been trying to serialize and deserialize a HashMap<integer,integer> that has one entry (1,1). but the entry seems to vanish after the serialization and deserialization. this is my code, it returns "true, false":</integer,integer>

    public static void main(String[] args) { // serialize
            JSONSerializer serializer = new JSONSerializer();
            JSONDeserializer<Map<Integer, Integer>> deserializer = new JSONDeserializer<Map<Integer, Integer>>();
    
            Map<Integer, Integer> tempMap = new HashMap<Integer, Integer>();
            tempMap.put(1, 1);
            String jsonStr = serializer.serialize(tempMap);
            Map<Integer, Integer> tempMap2 = deserializer.deserialize(jsonStr);
            System.out.println(tempMap.containsKey(1));
            System.out.println(tempMap2.containsKey(1));        
        }
    

    Thanks! :)

     
  • Charlie Hubbard

    Charlie Hubbard - 2015-10-03

    So this is a limitation of JSON standard. JSON standard only allows for strings in the key of objects. So you're creating a Map<integer,integer> which is effectively getting converted to Map<string,integer>. When that is deserialized you're getting a Map<string,integer> which you try to look up a Integer value of 1 which isn't there. If you looked up "1" you'd find your Integer 1 value.</string,integer></string,integer></integer,integer>

     

Log in to post a comment.

MongoDB Logo MongoDB