简体   繁体   中英

What the best way to convert from String to HashMap?

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}

使用JSON或XStream

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM