JsonDeserializerを使えば、自分でパースすることができます。
class Response {
String keyword;
String[] results;
public Response(String keyword, String[] results) {
this.keyword = keyword;
this.results = results;
}
}
class ResponseDeserializer implements JsonDeserializer<Response> {
@Override
public Response deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonArray jsonArray = json.getAsJsonArray();
String keyword = jsonArray.get(0).getAsString();
String[] results = new Gson().fromJson(jsonArray.get(1), String[].class);
return new Response(keyword, results);
}
}
こんな感じで定義しておいて、使うときに以下のように書きます。
Gson gson = new GsonBuilder()
.registerTypeAdapter(Response.class, new ResponseDeserializer())
.create();
Response[] responses = gson.fromJson(json, Response[].class);
逆にJsonに戻したい場合はJsonSerializerを作れば良いでしょう。
class ResponseSerializer implements JsonSerializer<Response> {
@Override
public JsonElement serialize(final Response src, Type typeOfSrc, JsonSerializationContext context) {
JsonArray array = new JsonArray();
array.add(src.keyword);
JsonArray results = new JsonArray();
for (String result : src.results) {
results.add(result);
}
array.add(results);
return array;
}
}
使うときは、以下のように。
Gson gson = new GsonBuilder()
.registerTypeAdapter(Response.class, new ResponseDeserializer())
.registerTypeAdapter(Response.class, new ResponseSerializer())
.create();
Response[] responses = gson.fromJson(json, Response[].class);
System.out.println(gson.toJson(responses));
output:
[["ここでは",["ここでは","個々では","此処では"]],["きものを",["着物を","きものを","キモノを"]],["ぬぐ",["脱ぐ","ぬぐ","ヌグ"]]]