I want to parse the Google CGI API for Japanese Input results in Gson.

Asked 2 years ago, Updated 2 years ago, 103 views

I would like to analyze the json returned by Google CGI API for Japanese Input using Gson, but I don't know what kind of Java class I should create to store the analysis results.
If anyone knows how to parse, I would appreciate it if you could let me know.

Google CGI API for Japanese Input provides the following json:

[
  ["Here",
    ["Here", "Individually", "Here"]
  ],
  ["Kimono",
    ["Kimono", "Kimono", "Kimono"]
  ],
  ["Wiping",
    ["Take it off", "Nug", "Nug"]
  ]
]

java json

2022-09-30 10:23

1 Answers

You can parse by yourself with JsonDeserializer.

class Response {
    String keyword;
    String [ ] results;

    publicResponse(String keyword, String[] results) {
        This.keyword=keyword;
        this.results=results;
    }
}

class ResponseDeserials implements JsonDeserials <Response> {

    @ Override
    publicResponse deserialize (JsonElement json, TypeOfT, JsonDeserializationContext context)
            US>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);
    }
}

Define it like this, and write it like this when you use it.

Gson=new GsonBuilder()
            .registerTypeAdapter(Response.class, newResponseDeser())
            .create();
    Response [ ] responses=gson.fromJson(json,Response[].class);

On the other hand, if you want to return to Json, you can create a JsonSerializer.

class ResponseSerializer implements JsonSerializer<Response>{

    @ Override
    public JsonElement serialize (final Response src, TypeOfSrc, JsonSerializationContext) {
        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;
    }
}

When using it, follow these steps:

Gson=new GsonBuilder()
            .registerTypeAdapter(Response.class, newResponseDeser())
            .registerTypeAdapter(Response.class, newResponseSerializer())
            .create();
    Response [ ] responses=gson.fromJson(json,Response[].class);

    System.out.println(gson.toJson(responses)));

output:

[["here", "here", "individually", "here", "here", "here", "here", "here", "Kimono", "Kimono", "Kimono", "Kimono"]], "Nug", "Nug", "Nug"]]]


2022-09-30 10:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.