java 如何将 hashMap 转换为 Json 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11851603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:39:26  来源:igfitidea点击:

how to convert hashMap to Json file

javagwt

提问by NewCodeLearner

I am leaning Java.

我正在学习 Java。

I have to transfer a Hashmap to Server using rpc.

我必须使用 rpc 将 Hashmap 传输到服务器。

HashMap

哈希表

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

how to do that.

怎么做。

采纳答案by Prso

See this link if its helps..

如果有帮助,请参阅此链接。

http://www.mkyong.com/java/how-to-convert-java-map-to-from-json-Hymanson/

http://www.mkyong.com/java/how-to-convert-java-map-to-from-json-Hymanson/

import com.fasterxml.Hymanson.databind.ObjectMapper;

ObjectMapper mapper = new ObjectMapper();
Map<String, String> testMap = new HashMap<String, String>(); 
testMap .put("1", "abc"); 
testMap .put("2", "ezc"); 
testMap .put("3", "afc"); 
testMap .put("4", "cvc"); 

      mapper.writeValue(new File("c:\user.json"), testMap);

回答by Steve Kuo

Take a look at Hymanson JSON processor. In particular the code will look something like:

看看Hymanson JSON 处理器。特别是代码看起来像:

Map map = your map
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(map);

If you want pretty JSON (multiple lines) for debugging, then use:

如果您想要漂亮的 JSON(多行)进行调试,请使用:

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

回答by Byter

you can also try GSONlibrary. It is fast and easy to use. The Below wrapper class will make your job even more easy

你也可以试试GSON图书馆。它快速且易于使用。下面的包装类将使您的工作更加轻松

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

All you need to do is

你需要做的就是

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

and you can easily get your original Objectback on the other side

你可以很容易地original Object回到other side

Map<String, String> newTestMap = ConvertJsonToObject.getFromJSON(json,Map.class);

回答by Alain BUFERNE

I don't catch : HashMap is Serializable so should be able to be used between client and server?

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