当我使用GSON将LinkedHashMap直接转换为JSON时,它可以正确转换,但是当我将其转换为class字段时,它不能正确转换。在我正在处理的另一个案例中,只有LinkedHashMap的最后一个元素出现在最终的JSON中。
public class Example {
public static void main(String[] args) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println("GSON HashMap!");
System.out.println(gson.toJson(hashMe()));
System.out.println("GSON Zone!");
//This doesn't give me the full LinkedHashMap
System.out.print(gson.toJson(zoneMe()));
}
public ZoneChild zoneMe() {
RateChild rate = new RateChild(hashMe());
ZoneChild zone = new ZoneChild();
zone.setName("Example");
zone.setRate(rate);
return zone;
}
public LinkedHashMap<Integer, String> hashMe() {
LinkedHashMap<Integer, String> rates = new LinkedHashMap<Integer, String>();
rates.put(60, "data1");
rates.put(25, "data2");
rates.put(15, "data3");
return rates;
}
public class Zone {
RateChild rate;
public Zone() {
}
public void setRate(RateChild rate) {
this.rate = rate;
}
}
public class ZoneChild extends Zone {
private int level;
private String name;
public ZoneChild() {
}
public void setName(String name) {
this.name = name;
}
public void setLevel(int level) {
this.level = level;
}
}
public class Rate {
LinkedHashMap<Integer, String> rate = new LinkedHashMap<Integer, String>();
public Rate(LinkedHashMap<Integer, String> rate) {
this.rate = rate;
}
}
//I need this class for specialization
public class RateChild extends Rate {
public RateChild(LinkedHashMap<Integer, String> rate) {
super(rate);
}
}
}
字符串
输出如下所示:
GSON HashMap!
{
"60": "data1",
"25": "data2",
"15": "data3"
}
GSON Zone!
{
"level": 0,
"name": "Example",
"rate": {
"rate": {}
}
}
型
我注意到,当LinkedHashMap字段直接位于JSON转换类(ZoneChild)中时,它不会失败。
1条答案
按热度按时间csga3l581#
无法重现。使用Java 2.10.1和Gson 2.10.1,以下代码按预期工作:
字符串
输出量:
型