从 String 转换为 HashMap 的最佳方法是什么?
我想将 Java HashMap 序列化为字符串表示形式。 HashMap 将仅包含原始值,例如字符串和整数。之后该字符串将被存储到 db 中。如何恢复HashMap? 使用 BeanUtils 和接口 Converter 还是使用 JSON?
例如:
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}
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}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 JSON 或 XStream。
Use JSON or XStream.
Jerry 博士是正确的,您应该做的是使用 ObjectOutputStream 序列化哈希图。这将允许您将字节写入数据库 BLOB 类型列,然后您可以将其反序列化回原始对象。要重复使用陈词滥调,为什么要重新发明轮子呢?在这种情况下您不想使用 Java 序列化有什么具体原因吗?
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?