How to convert hashmap to JSON object in Java

前端 未结 29 2513
谎友^
谎友^ 2020-11-22 11:20

How to convert or cast hashmap to JSON object in Java, and again convert JSON object to JSON string?

29条回答
  •  半阙折子戏
    2020-11-22 11:42

    If you use complex objects, you should apply enableComplexMapKeySerialization(), as stated in https://stackoverflow.com/a/24635655/2914140 and https://stackoverflow.com/a/26374888/2914140.

    Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
    Map original = new LinkedHashMap();
    original.put(new Point(5, 6), "a");
    original.put(new Point(8, 8), "b");
    System.out.println(gson.toJson(original));
    

    Output will be:

    {
     "(5,6)": "a",
     "(8,8)": "b"
    }
    

提交回复
热议问题