您可以通过编写代码,然后为注册一个自定义的序列化器
Step,并确保在其中使用
Duration而不是的方式来执行此操作
Data。
// registering your custom serializer:GsonBuilder builder = new GsonBuilder ();builder.registerTypeAdapter (Step.class, new StepSerializer ());Gson gson = builder.create ();// now use 'gson' to do all the work
下面是自定义序列化程序的代码,我在脑子里写下了代码。它会错过异常处理,并且可能无法编译,并且会降低创建
Gson重复实例的速度。但它代表了 这样的事情
,你会想做的事:
class StepSerializer implements JsonSerializer<Step>{ public JsonElement serialize (Step src, Type typeOfSrc, JsonSerializationContext context) { Gson gson = new Gson (); JsonObject step = new JsonObject (); step.add ("start_name", gson.toJsonTree (src.start_name); step.add ("end_name", gson.toJsonTree (src.end_name); step.add ("duration", gson.toJsonTree (src.data.duration); step.add ("distance", gson.toJsonTree (src.data.distance); step.add ("location", gson.toJsonTree (src.data.location); return step; }}


