Java 如何将hashMap转换为Json文件

Java 如何将hashMap转换为Json文件,java,gwt,Java,Gwt,我在学爪哇语 我必须使用rpc将哈希映射传输到服务器 哈希映射 Map<String, String> testMap = new HashMap<String, String>(); testMap .put("1", "abc"); testMap .put("2", "ezc"); testMap .put("3", "afc"); testMap .put("4", "cvc"); .. Map testMap=newhashmap(); testMap.put

我在学爪哇语

我必须使用rpc将哈希映射传输到服务器

哈希映射

Map<String, String> testMap = new HashMap<String, String>();
testMap .put("1", "abc");
testMap .put("2", "ezc");
testMap .put("3", "afc");
testMap .put("4", "cvc");
..
Map testMap=newhashmap();
testMap.put(“1”、“abc”);
testMap.put(“2”,“ezc”);
testMap.put(“3”、“afc”);
testMap.put(“4”,“cvc”);
..

如何做到这一点。

如果有帮助,请查看此链接

import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper=新的ObjectMapper();
Map testMap=newhashmap();
testMap.put(“1”、“abc”);
testMap.put(“2”,“ezc”);
testMap.put(“3”、“afc”);
testMap.put(“4”,“cvc”);
writeValue(新文件(“c:\\user.json”)、testMap;
看一看。特别是,代码将类似于:

Map map = your map
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(map);
如果您希望使用漂亮的JSON(多行)进行调试,请使用:

String json = mapper.defaultPrettyPrintingWriter().writeValueAsString(map);

您也可以尝试
GSON
library。它是快速和易于使用。 下面的包装器类将使您的工作更加简单

public class ConvertJsonToObject {

    private static Gson gson = new GsonBuilder().create();

    public static final <T> T getFromJSON(String json, Class<T> clazz) {
        return gson.fromJson(json, clazz);
    }

    public static final <T> String toJSON(T clazz) {
        return gson.toJson(clazz);
    }
}

我不明白:HashMap是可序列化的,所以应该可以在客户端和服务器之间使用?

相关:我不需要答案来告诉你如何使用Gson。为什么你的静态方法是final?:)@SteveKuo如果我不希望将来扩展该类,我通常会编写final。习惯了。我的错
public class ConvertJsonToObject {

    private static Gson gson = new GsonBuilder().create();

    public static final <T> T getFromJSON(String json, Class<T> clazz) {
        return gson.fromJson(json, clazz);
    }

    public static final <T> String toJSON(T clazz) {
        return gson.toJson(clazz);
    }
}
Map<String, String> testMap = new HashMap<String, String>();
testMap .put("1", "abc");
testMap .put("2", "ezc");
testMap .put("3", "afc");
testMap .put("4", "cvc");
String json = ConvertJsonToObject.toJSON(testMap);
Map<String, String> newTestMap = ConvertJsonToObject.getFromJSON(json,Map.class);