Last active
October 19, 2015 18:47
-
-
Save chrisjenx/9526544 to your computer and use it in GitHub Desktop.
Custom Gson Serialiser for android.support.v4.util.SimpleArrayMap;
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
return new GsonBuilder() | |
.registerTypeAdapter(SimpleArrayMapJsonSerializer.TYPE, new SimpleArrayMapJsonSerializer()) | |
.create(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.support.v4.util.SimpleArrayMap; | |
import com.google.gson.JsonElement; | |
import com.google.gson.JsonObject; | |
import com.google.gson.JsonSerializationContext; | |
import com.google.gson.JsonSerializer; | |
import com.google.gson.reflect.TypeToken; | |
import java.lang.reflect.Type; | |
/** | |
* Created by Chris Jenkins on 13/03/2014. | |
*/ | |
public class SimpleArrayMapJsonSerializer implements JsonSerializer<SimpleArrayMap> { | |
public static final Type TYPE = new TypeToken<SimpleArrayMap>() { | |
}.getType(); | |
@Override | |
public JsonElement serialize(final SimpleArrayMap src, final Type typeOfSrc, final JsonSerializationContext context) { | |
if (src == null) { | |
return null; | |
} | |
final JsonObject jsonObject = new JsonObject(); | |
final int length = src.size(); | |
Object k, v; | |
for (int i = 0; i < length; i++) { | |
k = src.keyAt(i); | |
v = src.valueAt(i); | |
jsonObject.add(String.valueOf(k), context.serialize(v)); | |
} | |
return jsonObject; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FYI this produces an JSONObject.
It will naturally use any other
serializers()
for your value so you can have complex data structures. or evenSimpleArrayMap<String,SimpleArrayMap<String,Object>
inception away!Worth noting that your key is always turned into a
String
as that is required for valid JSON. So make sure that if you are using objects as keys, their String representation is unique.