如何在值类型和键值对数量未知的情况下哈希映射 JSON 的键值对

Om *_*Sao 0 java json hashmap keyvaluepair

我有一个来自数据库的字符串格式的 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

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

我想将这些数据存储到我的哈希图中。我知道如果只能是 String: String 格式,我可以put在 Hashmap 中执行以下操作。

我的问题是

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

提前致谢 !

Tej*_*jal 5

你可以尝试下面的代码。

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());
Run Code Online (Sandbox Code Playgroud)