如何在Java中转换或转换哈希图到JSON对象,并再次将JSON对象转换为JSON字符串?


当前回答

    import org.json.JSONObject;

    HashMap<Object, Object> map = new HashMap<>();
    String[] list={"Grader","Participant"};
    String[] list1={"Assistant","intern"};
    map.put("TeachingAssistant",list);
    map.put("Writer",list1);
    JSONObject jsonObject = new JSONObject(map);
    System.out.printf(jsonObject.toString());

    // Result: {"TeachingAssistant":["Grader","Participant"],"Writer":["Assistant","intern"]}

其他回答

如果你正在使用net.sf.json.JSONObject,那么你不会在其中找到JSONObject(map)构造函数。您必须使用公共静态JSONObject fromObject(对象对象)方法。该方法接受JSON格式的字符串、map、dynabean和javabean。

JSONObject jsonObject = JSONObject.fromObject(myMap);

不需要Gson或JSON解析库。 只需使用新的JSONObject(Map<String, JSONObject>).toString(),例如:

/**
 * 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 "{}";
    }
}

对于使用TypeToken的更复杂的映射和列表,Gson是一种方式。getParameterized方法:

我们有一张这样的地图:

Map<Long, List<NewFile>> map;

我们使用上面提到的getParameterized方法来获取类型,如下所示:

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

然后使用Gson对象fromJson方法,使用mapflist对象,像这样:

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

上面提到的对象NewFile看起来是这样的:

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;
    }
}

反序列化的JSON是这样的:

{ “1”:[ { “id”:12232年, “文件名”:“test.html” }, { “id”:12233年, “文件名”:“file.txt” }, { “id”:12234年, “文件名”:“obj.json” } ], “2”:[ { “id”:122321年, “文件名”:“test2.html” }, { “id”:122332年, “文件名”:“file2.txt” }, { “id”:122343年, “文件名”:“obj2.json” } ] }

以下是我与GSON的单线解决方案:

myObject = new Gson().fromJson(new Gson().toJson(myHashMap), MyClass.class);

就我而言,我不想要任何依赖。使用Java 8,你可以得到一个JSON字符串,如下所示:

Map<String, Object> map = new HashMap<>();
map.put("key", "value");
map.put("key2", "value2");
String json = "{"+map.entrySet().stream()
    .map(e -> "\""+ e.getKey() + "\":\"" + String.valueOf(e.getValue()) + "\"")
    .collect(Collectors.joining(", "))+"}";