How to convert hashmap to JSON object in Java

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

    If you don't really need HashMap then you can do something like that:

    String jsonString = new JSONObject() {{
      put("firstName", user.firstName);
      put("lastName", user.lastName);
    }}.toString();
    

    Output:

    {
      "firstName": "John",
      "lastName": "Doe"
    }
    

提交回复
热议问题