gpt4 book ai didi

java - 如何在值类型和键值对数量未知的情况下 HashMap JSON 的键值对

转载 作者:行者123 更新时间:2023-12-01 17:54:37 24 4
gpt4 key购买 nike

我有一个来自数据库的字符串格式的 JSON,我只知道它是键值格式的。我事先不知道

  • JSON 字符串中有多少对
  • 值类型。它可以是字符串或对象。

以下是我的一些 JSON 字符串:

  • {"windowHandle":"current"} \\ in one String: String format
  • {"type":"implicit","ms":100000} \\ in two String: String format
  • {"id":"{a67fc38c-10e6-4c5e-87dc-dd45134db570}"} \\ in one String: String format
  • {"key1": {"sub-key1": "sub-value1", "sub-key2": "sub-value2"}, "key2": {"sub-key2": "sub-value2"}} \\ in two String: Object format

所以,基本上:键值对的数量和值的类型(字符串,对象)事先是未知的。

我想将这些数据存储到我的 HashMap 中。我知道如果只能是 String: String 格式,我可以这样做 put在 HashMap 中。

我的问题是

  • 在这种情况下如何有效地存储 json 而无需迭代 JSON 字符串。
  • 我的 Hashmap 类型应该是什么,绝对不是 HashMap <String, String>

提前致谢!

最佳答案

您可以尝试以下代码。

List<Map<String, Object>> mapdataList = new ArrayList<Map<String, Object>>();

Map<String, Object> MapObj = new HashMap<String, Object>();
MapObj.put("windowHandle", "current");
MapObj.put("id", "{a67fc38c-10e6-4c5e-87dc-dd45134db570}");
mapdataList.add(MapObj);

Gson gson = new Gson();
JsonObject jObject = new JsonObject();
JsonParser jP = new JsonParser();
jObject.add("data", jP.parse(gson.toJson(mapdataList)));
System.out.println(jObject.toString());

关于java - 如何在值类型和键值对数量未知的情况下 HashMap JSON 的键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46312750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com