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

dhr*_*hrm 8 java json gson

我正在使用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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

当前一个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
  }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能使用 GSON 做到这一点?

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

Arj*_*kar 6

您可以通过编写,然后为 注册自定义序列化程序Step,并确保在其中使用Durationetc 而不是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
Run Code Online (Sandbox Code Playgroud)

下面的自定义序列化器的代码,我正在写下我的头顶。它错过了异常处理,可能无法编译,并且会降低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;
    }
}
Run Code Online (Sandbox Code Playgroud)