本课程
public class Data {
Map<String, Class<?>> dataTypes = new HashMap<String, Class<?>>();
}
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.serializeNulls()
.create();
Data d = new Data();
d.dataTypes.put("DateParameter", java.util.Date.class);
System.out.println("Data is " + gson.toJson(d));
打印以下内容:
数据为{“dataTypes”:{“DateParameter”:{“annotationType”:null}}}
如何打印正确的班级类型?
答案 0 :(得分:1)
我认为你必须为custom json de/serializer编写自己的Class
class。尝试这样的事情:
public static class ClassSerializer implements
JsonSerializer<Class>, JsonDeserializer<Class> {
public JsonElement serialize(Class klass, Type type, JsonSerializationContext ctx) {
return new JsonPrimitive(klass.getCanonicalName());
}
public Class deserialize(JsonElement el, Type type, JsonDeserializationContext ctx) throws JsonParseException {
try {
return Class.forName(el.getAsJsonPrimitive().getAsString());
} catch (ClassNotFoundException cnfe) {
throw new JsonParseException(cnfe);
}
}
}
// ...
public static void main(String args[]) {
Gson gson = new GsonBuilder()
.registerTypeAdapter(Class.class, new ClassSerializer())
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.serializeNulls()
.create();
Data d = new Data();
d.dataTypes.put("DateParameter", java.util.Date.class);
gson.toJson(d); // => {"dataTypes":{"DateParameter":"java.util.Date"}}