Skip to content

Instantly share code, notes, and snippets.

@chrisjenx
Last active October 19, 2015 18:47
Show Gist options
  • Select an option

  • Save chrisjenx/9526544 to your computer and use it in GitHub Desktop.

Select an option

Save chrisjenx/9526544 to your computer and use it in GitHub Desktop.
Custom Gson Serialiser for android.support.v4.util.SimpleArrayMap;
return new GsonBuilder()
.registerTypeAdapter(SimpleArrayMapJsonSerializer.TYPE, new SimpleArrayMapJsonSerializer())
.create();
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;
}
}
@chrisjenx

Copy link
Copy Markdown
Author

FYI this produces an JSONObject.

It will naturally use any other serializers() for your value so you can have complex data structures. or even SimpleArrayMap<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.

{
  "key" : "value",
  "key2" : "somethingElse",
  "hashValueOfKeyObject" :  {
    "name" : "value"
  }
}

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