How to convert hashmap to JSON object in Java

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

    First convert all your objects into valid Strings

    HashMap<String, String> params = new HashMap<>();
    params.put("arg1", "<b>some text</b>");
    params.put("arg2", someObject.toString());
    

    Then insert the entire map into a org.json.JSONObject

    JSONObject postData = new JSONObject(params);
    

    Now you can get the JSON by simply calling the object's toString

    postData.toString()
    //{"arg1":"<b>some text<\/b>" "arg2":"object output"}
    

    Create a new JSONObject

    JSONObject o = new JSONObject(postData.toString());
    

    Or as a byte array for sending over HTTP

    postData.toString().getBytes("UTF-8");
    
    0 讨论(0)
  • 2020-11-22 11:58

    You can use:

    new JSONObject(map);
    

    Caution: This will only work for a Map<String, String>!

    Other functions you can get from its documentation
    http://stleary.github.io/JSON-java/index.html

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

    This solution works with complex JSONs:

    public Object toJSON(Object object) throws JSONException {
        if (object instanceof HashMap) {
            JSONObject json = new JSONObject();
            HashMap map = (HashMap) object;
            for (Object key : map.keySet()) {
                json.put(key.toString(), toJSON(map.get(key)));
            }
            return json;
        } else if (object instanceof Iterable) {
            JSONArray json = new JSONArray();
            for (Object value : ((Iterable) object)) {
                json.put(toJSON(value));
            }
            return json;
        }
        else {
            return object;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 11:59

    This is typically the work of a Json library, you should not try to do it yourself. All json libraries should implement what you are asking for, and you can find a list of Java Json libraries on json.org, at the bottom of the page.

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

    Gson way for a bit more complex maps and lists using TypeToken.getParameterized method:

    We have a map that looks like this:

    Map<Long, List<NewFile>> map;
    

    We get the Type using the above mentioned getParameterized method like this:

    Type listOfNewFiles = TypeToken.getParameterized(ArrayList.class, NewFile.class).getType();
    Type mapOfList = TypeToken.getParameterized(LinkedHashMap.class, Long.class, listOfNewFiles).getType();
    

    And then use the Gson object fromJson method like this using the mapOfList object like this:

    Map<Long, List<NewFile>> map = new Gson().fromJson(fileContent, mapOfList);
    

    The mentioned object NewFile looks like this:

    class NewFile
    {
        private long id;
        private String fileName;
    
        public void setId(final long id)
        {
            this.id = id;
        }
    
        public void setFileName(final String fileName)
        {
            this.fileName = fileName;
        }
    }
    

    The deserialized JSON looks like this:

    {
      "1": [
        {
          "id": 12232,
          "fileName": "test.html"
        },
        {
          "id": 12233,
          "fileName": "file.txt"
        },
        {
          "id": 12234,
          "fileName": "obj.json"
        }
      ],
     "2": [
        {
          "id": 122321,
          "fileName": "test2.html"
        },
        {
          "id": 122332,
          "fileName": "file2.txt"
        },
        {
          "id": 122343,
          "fileName": "obj2.json"
        }
      ]
    }

    0 讨论(0)
提交回复
热议问题