转换Map< Integer,Object>用GSON转换为JSON? [英] Convert Map<Integer, Object> to JSON with GSON?
本文介绍了转换Map< Integer,Object>用GSON转换为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Hee Guys
我很好奇是否可以通过GSON将Map转换为JSON,反之亦然?我放入的对象已经通过GSON从JSON转换为对象.
I'm curious if it is possible to convert a Map to JSON and vica versa with GSON? The object that i'm putting in is already converted to a Object from JSON with GSON.
我正在使用的对象看起来像这样:
Object that i'm using looks like this:
public class Locations{
private List<Location> location;
<-- Getter / Setter -->
public class Location{
<-- Fields and Getters/Setters -->
}
}
推荐答案
假设您使用的是java.util.Map
:
Map<Integer, Object> map = new HashMap<>();
map.put(1, "object");
// Map to JSON
Gson gson = new Gson(); // com.google.gson.Gson
String jsonFromMap = gson.toJson(map);
System.out.println(jsonFromMap); // {"1": "object"}
// JSON to Map
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> map = gson.fromJson(json, type);
for (String key : map.keySet()) {
System.out.println("map.get = " + map.get(key));
}
这篇关于转换Map< Integer,Object>用GSON转换为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文