Skip to content

Adapter not working for Map key #77

@jansupol

Description

@jansupol

I'm trying to use adapters to serialize a Map of two objects. Adapter is working fine for value but not working for the key.
Example :

public class TestJsonB {

    public static void main(String[] args) {

        TestJsonB tB = new TestJsonB();
        TestAdapter test = tB.new TestAdapter();
        Map<Type, Status> mapTest = new HashMap<>();
        mapTest.put(Type.OIDVAL, Status.ACTIVE);
        test.setMap(mapTest);

        Jsonb jsonB = SerializationUtils.getJSONBuilder(false, tB.new TypeAdapter(), tB.new StatusAdapter());
        System.out.println(jsonB.toJson(test));

    }

    class TestAdapter {
        Map<Type, Status> map;

        /**
         * @return the map
         */
        public Map<Type, Status> getMap() {
            return map;
        }

        /**
         * @param map
         *            the map to set
         */
        public void setMap(Map<Type, Status> map) {
            this.map = map;
        }
    }

    enum Type {
        OIDVAL, MSISDN;
    }

    enum Status {
        ACTIVE, INACTIVE;
    }

    class TypeAdapter implements JsonbAdapter<Type, String> {

        @Override
        public String adaptToJson(Type obj) throws Exception {
            return obj.name().toLowerCase();
        }

        @Override
        public Type adaptFromJson(String obj) throws Exception {
            return Type.valueOf(obj);
        }

    }

    class StatusAdapter implements JsonbAdapter<Status, String> {

        @Override
        public String adaptToJson(Status obj) throws Exception {
            return obj.name().toLowerCase();
        }

        @Override
        public Status adaptFromJson(String obj) throws Exception {
            return Status.valueOf(obj);
        }

    }

}

Output is :

{"map":{"OIDVAL":"active"}}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions