gson-typeadapter

I encountered a problem in a recent project, that is, when Gson parses an empty array, what if the problem can be solved elegantly by ignoring the background? The answer is-serialization and deserialization of Gson:

public class ResultDeserializer implements JsonDeserializer<BaseResult> {
    
    
    @Override
    public BaseResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject obj = json.getAsJsonObject();
        //下面添加你要做的事情
        if (obj.get("result") != null) {
            if (obj.get("result").isJsonObject() && obj.getAsJsonObject("result").has("message") && obj.getAsJsonObject("result").entrySet().size() == 1) {
                obj.getAsJsonObject("result").remove("message");
            }
            if (obj.get("result").toString().equals("{}")) {
                obj.remove("result");
            }
        }

        BaseResult baseResult = new Gson().fromJson(json, typeOfT);
        if (obj.has("success")&&obj.get("success").getAsString().equals("true")) {
            baseResult.setSuccess(true);
        } else {
            baseResult.setSuccess(false);
        }
        if (obj.isJsonNull()) {
            baseResult.setSuccess(false);
        }
        baseResult.setErrorcode(obj.has("errorcode") ? obj.get("errorcode").getAsString() : "");
        baseResult.setErrorcode(obj.has("error") ? obj.get("errorcode").getAsString() : "");
        return baseResult;
    }
}

Then register this typeadapter

Gson gson=new GsonBuilder()
      .registerTypeAdapter(BaseResult.class, new ResultDeserializer())
      .create();

Then it's fine, you can write a basic class of a generic Bean, and then you can use it globally, such as:

public class BaseResult<T> implements Serializable {
    
    
    private Boolean success;
    private String errorcode;
    private String error;
    private T result;
}

registerTypeAdapter It also supports a variety of types, you can find time to study:

  • JsonSerializer <?>
  • JsonDeserializer <?>
  • InstanceCreator <?>
  • TypeAdapter <?>

Guess you like

Origin blog.csdn.net/Ser_Bad/article/details/64246499