How to convert hashmap to JSON object in Java

前端 未结 29 2354
谎友^
谎友^ 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:32

    In my case I didn't want any dependancies. Using Java 8 you can get JSON as a string this simple:

    Map map = new HashMap<>();
    map.put("key", "value");
    map.put("key2", "value2");
    String json = "{"+map.entrySet().stream()
        .map(e -> "\""+ e.getKey() + "\"" + ":\"" + String.valueOf(e.getValue()) + "\"")
        .collect(Collectors.joining(", "))+"}";
    

提交回复
热议问题