How to convert hashmap to JSON object in Java

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

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

    We have a map that looks like this:

    Map> 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> 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"
        }
      ]
    }

提交回复
热议问题