小编典典

GSON:如何将字段移动到父对象

json

我正在使用Google GSON将Java对象转换为JSON。

目前,我具有以下结构:

"Step": {
  "start_name": "Start",
  "end_name": "End",
  "data": {
    "duration": {
      "value": 292,
      "text": "4 min."
    },
    "distance": {
       "value": 1009.0,
       "text": "1 km"
    },
    "location": {
       "lat": 59.0000,
       "lng": 9.0000,
       "alt": 0.0
    }
  }
}

当前,Duration对象在Data对象内部。我想跳过Data对象并将对象移动DurationStep对象,如下所示:

"Step": {
  "start_name": "Start",
  "end_name": "End",
  "duration": {
    "value": 292,
    "text": "4 min."
  },
  "distance": {
     "value": 1009.0,
     "text": "1 km"
  },
  "location": {
     "lat": 59.0000,
     "lng": 9.0000,
     "alt": 0.0
  }
}

如何使用GSON做到这一点?

编辑:我试图使用TypeAdapter来修改Step.class,但是在写入方法中,我无法将我的工时对象添加到JsonWriter中。


阅读 263

收藏
2020-07-27

共1个答案

小编典典

您可以通过编写代码,然后为注册一个自定义的序列化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 ();
      /* Whenever Step is serialized,
      serialize the contained Data correctly.  */
      JsonObject step = new JsonObject ();
      step.add ("start_name", gson.toJsonTree (src.start_name);
      step.add ("end_name",   gson.toJsonTree (src.end_name);

      /* Notice how I'm digging 2 levels deep into 'data.' but adding
      JSON elements 1 level deep into 'step' itself.  */
      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;
    }
}
2020-07-27