views:

161

answers:

2

I would like to serialize a Java HashMap to string representation. The HashMap will contains only primitive values like string and integer. After that this string will be stored to db. How to restore back the HashMap? Is it make sense to use BeanUtils and interface Converter or use JSON?

For example:

    List list = new ArrayList();
    list.add(new Long(1));
    list.add(new Long(2));
    list.add(new Long(4)); 

    Map map = new HashMap();
    map.put("cityId", new Integer(1));
    map.put("name", "test");
    map.put("float", new Float(-3.2));
    map.put("ids", list);

    map.toString() -> {float=-3.2,ids=[1, 2, 4],name=test,cityId=1}
    map.toJSON ->     {"float":-3.2,"ids":[1,2,4],"name":"test","cityId":1}
+1  A: 

Use JSON or XStream.

Sjoerd
parsing xml is more expensive than JSON in this case
eugenn
A: 

Dr Jerry is correct, what you should do is serialize the hash map using ObjectOutputStream. This will let you write the bytes to a database BLOB type column and then you can de-serialize it back to your original object. To re-use a tired cliche, why re-invent the wheel? Is there a specific reason you don't want to use Java serialization in this case?

Java Drinker
I don't want to serialize as a binary because it leads to different desertification issues and it's require use a BLOB type
eugenn
Hmm, ok if using a BLOB is not feasible, then I like the JSON way as well, not the greatest, but works well. Google's GSON looks like it might do the trick for you. It supports java collections etc... check it out here:http://sites.google.com/site/gson/gson-user-guide
Java Drinker