Storing HashMap<String, Object> with using ActiveAndroid library

断了今生、忘了曾经 提交于 2019-12-04 18:18:31

ActiveAndroid don't persist Map type by default.

Yes, you are right, you must write your own TypeSerializer, to serialize this Map as an String in some format (e.g: JSON) and deserialize the String to your Map.

Maybe this code can help you to start this:

final public class UtilMapSerializer extends TypeSerializer {
    @Override
    public Class<?> getDeserializedType() {
        return Map.class;
    }

    @Override
    public Class<?> getSerializedType() {
        return String.class;
    }

    @Override
    public String serialize(Object data) {
        if (data == null) {
            return null;
        }

        // Transform a Map<String, Object> to JSON and then to String
        return new JSONObject((Map<String, Object>) data).toString();
    }

    @Override
    public Map<String, Object> deserialize(Object data) {
        if (data == null) {
            return null;
        }

        // Properties of Model
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            JSONObject json = new JSONObject((String) data);

            for(Iterator it = json.keys(); it.hasNext();) {
                String key = (String) it.next();

                map.put(key, json.get(key));
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return map;
    }
}

And register then as <meta-data> in your <Application>.

<meta-data android:name="AA_SERIALIZERS" android:value="my.package.UtilMapSerializer" />

More information: https://github.com/pardom/ActiveAndroid/wiki/Type-serializers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!