我想使用GSON将下面的Example类序列化为JSON。
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.LinkedHashMap;
public class Example
{
private LinkedHashMap<String,Object> General;
private static final String VERSION="Version";
private static final String RANGE="Range";
private static final String START_TIME="Start_Time";
private static final String END_TIME="End_Time";
public Example() {
General = new LinkedHashMap<String,Object>();
General.put(VERSION, "0.1");
LinkedHashMap<String,String> Range = new LinkedHashMap<String, String>();
Range.put(START_TIME, "now");
Range.put(END_TIME, "never");
General.put(RANGE, Range);
}
public String toJSON() {
Gson gson = new GsonBuilder().serializeNulls().create();
return gson.toJson(this);
}
}
我期望获得以下输出:
{"General":{"Version":"0.1","Range":{"Start_Time":"now","End_Time":"never"}}}
但调用 toJSON()
函数会返回
{"General":{"Version":"0.1","Range":{}}}
看起来 GSON 无法对 Map 中的 Range 对象进行序列化,这是 GSON 的限制还是我的操作有误?