简体   繁体   English

如何在不知道值类型和键值对数量的情况下哈希JSON的键值对

[英]How to hashmap a JSON's key-value pair where Value type and number of key-value pairs not known

I have a JSON in string format coming from DB, about which I only know that it's in key-value format. 我有一个来自数据库的字符串格式的JSON,对此我只知道它是键值格式。 I don't know beforehand 我不知道

  • How many pairs will be there in JSON string JSON字符串中将有多少对
  • type-of Value. 类型值。 It can be String or Object. 它可以是字符串或对象。

Here are some of my JSON String: 这是我的一些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

So, basically: Number of key-value pair and type of value(String, Object) is not known beforehand. 因此,基本上:键值对的数量和值的类型(字符串,对象)事先未知。

I want to store this data into my Hashmap. 我想将此数据存储到我的Hashmap中。 I know that if could be only String: String format, I could do as following put in the Hashmap. 我知道,如果可以只字符串:字符串格式,我可以做如下put在HashMap中。

My question is , 我的问题是

  • How I can store json in this case efficiently without iterating over JSON String. 在这种情况下,如何在不迭代JSON String的情况下有效地存储JSON。
  • What should be my Hashmap type, definetily not HashMap <String, String> ? 我的Hashmap类型应该是什么,绝对不是HashMap <String, String>

Thanks in Advance ! 提前致谢 !

you can try following code. 您可以尝试以下代码。

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());

You can use the com.fasterxml.jackson.databind.ObjectMapper or Gson to convert the String into a Map<String, Object> . 您可以使用com.fasterxml.jackson.databind.ObjectMapperGson将String转换为Map<String, Object>

Here is an example using Gson 这是使用Gson的示例

public static void main(String[] args) {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    Map map = gson.fromJson("{\"var\":\"value\"}", Map.class);
    System.out.println("map = " + map);
}

You can get an example of the ObjectMapper in action over here . 您可以在此处获得运行中的ObjectMapper的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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