Skip to content

Instantly share code, notes, and snippets.

@beilly
Last active August 21, 2018 09:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beilly/a85331c1cdf432d2e4df2289cd7cdf15 to your computer and use it in GitHub Desktop.
Save beilly/a85331c1cdf432d2e4df2289cd7cdf15 to your computer and use it in GitHub Desktop.
处理 Empty Json Object to null,no Property Jsonobject to null

用法

new GsonBuilder()  
            .registerTypeAdapterFactory(
                new EmptyCheckTypeAdapterFactory())
            .create();

thinks: chrisjenx

package com.ibeilly.utils.gson;
import android.os.Parcelable;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
/**
* @author shibl
* @date 2018/5/4
**/
public class EmptyCheckTypeAdapterFactory implements TypeAdapterFactory {
@Override public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
// We filter out the EmptyCheckTypeAdapter as we need to check this for emptiness!
if (Parcelable.class.isAssignableFrom(type.getRawType())) {
final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
return new EmptyCheckTypeAdapter<>(delegate, elementAdapter).nullSafe();
}
return null;
}
public static class EmptyCheckTypeAdapter<T> extends TypeAdapter<T> {
private final TypeAdapter<T> delegate;
private final TypeAdapter<JsonElement> elementAdapter;
public EmptyCheckTypeAdapter(final TypeAdapter<T> delegate,
final TypeAdapter<JsonElement> elementAdapter) {
this.delegate = delegate;
this.elementAdapter = elementAdapter;
}
@Override public void write(final JsonWriter out, final T value) throws IOException {
this.delegate.write(out, value);
}
@Override public T read(final JsonReader in) throws IOException {
final JsonObject asJsonObject = elementAdapter.read(in).getAsJsonObject();
if (asJsonObject.entrySet().isEmpty()) return null;
return this.delegate.fromJsonTree(asJsonObject);
}
}
}
@beilly
Copy link
Author

beilly commented May 4, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment