从 String 转换为 HashMap 的最佳方法是什么?

发布于 2024-09-05 20:56:27 字数 734 浏览 0 评论 0原文

我想将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

七秒鱼° 2024-09-12 20:56:27

使用 JSON 或 XStream

Use JSON or XStream.

预谋 2024-09-12 20:56:27

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文