Skip to content

Instantly share code, notes, and snippets.

@dmarcato
Last active May 21, 2020 10:25
Show Gist options
  • Save dmarcato/6455221 to your computer and use it in GitHub Desktop.
Save dmarcato/6455221 to your computer and use it in GitHub Desktop.
De/Serialization of generic SparseArray using Gson library
import android.util.SparseArray;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
public class Main {
public static class MyCustomClass {
public int a;
public String b;
}
public static void main(String[] args) {
Type sparseArrayType = new TypeToken<SparseArray<MyCustomClass>>() {}.getType();
Gson gson = new GsonBuilder()
.registerTypeAdapter(sparseArrayType, new SparseArrayTypeAdapter<MyCustomClass>(MyCustomClass.class))
.create();
}
}
import android.util.SparseArray;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.lang.reflect.Type;
public class SparseArrayTypeAdapter<T> extends TypeAdapter<SparseArray<T>> {
private final Gson gson = new Gson();
private final Class<T> classOfT;
private final Type typeOfSparseArrayOfT = new TypeToken<SparseArray<T>>() {}.getType();
private final Type typeOfSparseArrayOfObject = new TypeToken<SparseArray<Object>>() {}.getType();
public SparseArrayTypeAdapter(Class<T> classOfT) {
this.classOfT = classOfT;
}
@Override
public void write(JsonWriter jsonWriter, SparseArray<T> tSparseArray) throws IOException {
if (tSparseArray == null) {
jsonWriter.nullValue();
return;
}
gson.toJson(gson.toJsonTree(tSparseArray, typeOfSparseArrayOfT), jsonWriter);
}
@Override
public SparseArray<T> read(JsonReader jsonReader) throws IOException {
if (jsonReader.peek() == JsonToken.NULL) {
jsonReader.nextNull();
return null;
}
SparseArray<Object> temp = gson.fromJson(jsonReader, typeOfSparseArrayOfObject);
SparseArray<T> result = new SparseArray<T>(temp.size());
int key;
JsonElement tElement;
for (int i = 0; i < temp.size(); i++) {
key = temp.keyAt(i);
tElement = gson.toJsonTree(temp.get(key));
result.put(key, gson.fromJson(tElement, classOfT));
}
return result;
}
}
@Mr-wangyong
Copy link

this is can not work to parse sparseArray,How do it

@Miha-x64
Copy link

@yccheok short answer is no, main is here for testing purposes or as an example.

@pawelkw
Copy link

pawelkw commented Feb 7, 2018

I owe you a beer.

@tomalf2
Copy link

tomalf2 commented Mar 29, 2018

Thanks, I owe you a beer too!

@ThirupathiMukkera
Copy link

not working in one plus devices with android Q.

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