[英]Java Map to JSON string
I need to convert a map to JSON string, I am using a third-party library and one of the classes in it has a field of type Map<String, Object>
I need to convert that map to JSON string and send it to its destination. I need to convert a map to JSON string, I am using a third-party library and one of the classes in it has a field of type
Map<String, Object>
I need to convert that map to JSON string and send it to its目的地。 All works ok until I put a string into that map as a value ie if that Object
in the map is a String
then I end up having four double quotes ( ""value""
) in the final JSON string I get from jackson
's OBJECT_MAPPER.writeValueAsString(str)
method. All works ok until I put a string into that map as a value ie if that
Object
in the map is a String
then I end up having four double quotes ( ""value""
) in the final JSON string I get from jackson
's OBJECT_MAPPER.writeValueAsString(str)
方法。
eg the following this map:例如下面这个 map:
map.put("key", "value")
of type Map<String, Object>
will result in {"key": ""value""}
which obviously is not a JSON string, any idea how to resolve this without writing a custom method to check types and solve the issue? Map<String, Object>
类型的map.put("key", "value")
将导致{"key": ""value""}
这显然不是 JSON 字符串,知道如何在不写入的情况下解决此问题检查类型并解决问题的自定义方法?
Try to use com.google.gson.Gson尝试使用 com.google.gson.Gson
public void convertMapToJson() {
SortedMap<String, String> elements = new TreeMap();
elements.put("Key1", "Value1");
elements.put("Key2", "Value2");
elements.put("Key3", "Value3");
Gson gson = new Gson();
Type gsonType = new TypeToken<HashMap>(){}.getType();
String gsonString = gson.toJson(elements,gsonType);
System.out.println(gsonString);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.