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 } } }
目前, Duration
对象位于Data
对象内。 我想跳过Data
对象并将Duration
对象移动到Step
对象,如下所示:
"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,但在write-method中我无法将持续时间对象添加到JsonWriter。
您可以通过编写,然后为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
下面是自定义序列化程序的代码,我正在写下我的头脑。 它错过了exception处理,可能无法编译,并且确实会减慢重复创建Gson
实例的速度。 但它代表了你想要做的事情:
class StepSerializer implements JsonSerializer { 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; } }
我认为在gson中没有漂亮的方法。 也许从初始json获取java对象(Map),删除数据,将持续时间和序列化添加到json:
Map initial = gson.fromJson(initialJson); // Replace data with duration in this map Map converted = ... String convertedJson = gson.toJson(converted);