How to convert hashmap to JSON object in Java

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

    Example using json

    Map data = new HashMap();
        data.put( "name", "Mars" );
        data.put( "age", 32 );
        data.put( "city", "NY" );
        JSONObject json = new JSONObject();
        json.putAll( data );
        System.out.printf( "JSON: %s", json.toString(2) );
    

    output::

    JSON: {
      "age": 32,
      "name": "Mars",
      "city": "NY"
    }
    

    You can also try to use Google's GSON.Google's GSON is the best library available to convert Java Objects into their JSON representation.

    http://code.google.com/p/google-gson/

提交回复
热议问题