How to convert hashmap to JSON object in Java

前端 未结 29 2005
谎友^
谎友^ 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<String, Object> data = new HashMap<String, Object>();
        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/

    0 讨论(0)
  • 2020-11-22 11:37

    If you are using JSR 374: Java API for JSON Processing ( javax json ) This seems to do the trick:

        JsonObjectBuilder job = Json.createObjectBuilder((Map<String, Object>) obj);
        JsonObject jsonObject = job.build();
    
    0 讨论(0)
  • 2020-11-22 11:39

    No need for Gson or JSON parsing libraries. Just using new JSONObject(Map<String, JSONObject>).toString(), e.g:

    /**
     * convert target map to JSON string
     *
     * @param map the target map
     * @return JSON string of the map
     */
    @NonNull public String toJson(@NonNull Map<String, Target> map) {
        final Map<String, JSONObject> flatMap = new HashMap<>();
        for (String key : map.keySet()) {
            try {
                flatMap.put(key, toJsonObject(map.get(key)));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        try {
            // 2 indentSpaces for pretty printing
            return new JSONObject(flatMap).toString(2);
        } catch (JSONException e) {
            e.printStackTrace();
            return "{}";
        }
    }
    
    0 讨论(0)
  • 2020-11-22 11:40

    You can convert Map to JSON using Jackson as follows:

    Map<String,Object> map = new HashMap<>();
    //You can convert any Object.
    String[] value1 = new String[] { "value11", "value12", "value13" };
    String[] value2 = new String[] { "value21", "value22", "value23" };
    map.put("key1", value1);
    map.put("key2", value2);
    map.put("key3","string1");
    map.put("key4","string2");
    
    String json = new ObjectMapper().writeValueAsString(map);
    System.out.println(json);
    

    Maven Dependencies for Jackson :

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.5.3</version>
        <scope>compile</scope>
    </dependency>
    
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.5.3</version>
        <scope>compile</scope>
    </dependency>
    

    If you are using JSONObject library, you can convert map to JSON as follows:

    Map<String, Object> map = new HashMap<>();
    // Convert a map having list of values.
    String[] value1 = new String[] { "value11", "value12", "value13" };
    String[] value2 = new String[] { "value21", "value22", "value23" };
    map.put("key1", value1);
    map.put("key2", value2);
    
    JSONObject json = new JSONObject(map);
    System.out.println(json);
    

    Maven Dependencies for JSONObject :

    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20140107</version>
    </dependency>
    

    Hope this will help. Happy coding.

    0 讨论(0)
  • 2020-11-22 11:40

    Here my single-line solution with GSON:

    myObject = new Gson().fromJson(new Gson().toJson(myHashMap), MyClass.class);
    
    0 讨论(0)
  • 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<Point, String> original = new LinkedHashMap<Point, String>();
    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"
    }
    
    0 讨论(0)
提交回复
热议问题