Skip to content Skip to sidebar Skip to footer

Json To Hashmap (jackson)

I want to convert JSON to a HashMap with Jackson. This is my JSON: String json = '[{\'Opleidingen\':[{\'name\':\'Bijz. trajecten zorg en welzijn\',\'afk\':\'BTZW\',\'id\':\'0\'},{\

Solution 1:

I think, you should separate deserialization logic from the way how to retrieve names at the end. For deserialization use as simle method as you can. For example, you can create POJO classes which describe your JSON. See below example. POJO classes:

classEntitiesOwner {

    privateString name;
    privateList<Entity> entities;

    @JsonAnySetterpublicvoidsetProperties(String name, List<Entity> entities) {
        this.name = name;
        this.entities = entities;
    }

    publicStringgetName() {
        return name;
    }

    publicList<Entity> getEntities() {
        return entities;
    }

    @OverridepublicStringtoString() {
        return"EntitiesOwner [name=" + name + ", entities=" + entities + "]";
    }
}

classEntity {

    private int id;
    privateString afk;
    privateString name;

    public int getId() {
        return id;
    }

    publicvoidsetId(int id) {
        this.id = id;
    }

    publicStringgetAfk() {
        return afk;
    }

    publicvoidsetAfk(String afk) {
        this.afk = afk;
    }

    publicvoidsetCat(String cat) {
        this.afk = cat;
    }

    publicStringgetName() {
        return name;
    }

    publicvoidsetName(String name) {
        this.name = name;
    }

    @OverridepublicStringtoString() {
        return"Entity [id=" + id + ", afk=" + afk + ", name=" + name + "]";
    }
}

Now you can easily deserialize it in this way:

ObjectMapper mapper = new ObjectMapper();

EntitiesOwner[] owners = mapper.readValue(json, EntitiesOwner[].class);
System.out.println(Arrays.toString(owners));

Above program prints:

[EntitiesOwner [name=Opleidingen, entities=[Entity [id=0, afk=BTZW, name=Bijz. trajecten zorg en welzijn], Entity [id=14, afk=Bwk, name=Bouwkunde], Entity [id=15, afk=EltMe, name=Electrotechniek / mechatronica], Entity [id=16, afk=Extern, name=Extern], Entity [id=17, afk=Zorg, name=Gezondheidszorg], Entity [id=18, afk=Hand, name=Handel], Entity [id=19, afk=Hor, name=Horeca], Entity [id=20, afk=ICT, name=Ict], Entity [id=21, afk=MZ, name=Maatschappelijke zorg], Entity [id=22, afk=OAPW, name=Onderwijs assistent / pedagogisch werk], Entity [id=23, afk=TAB, name=Tab / brug], Entity [id=24, afk=WtbMt, name=Werktuigbouw / maritieme techniek], Entity [id=25, afk=TAB, name=Zakelijke dienstverlening]]], EntitiesOwner [name=Klassen, entities=[Entity [id=1, afk=BTZW, name=V2ZWA], Entity [id=2, afk=Bwk, name=V2ZWB], Entity [id=3, afk=BTZW, name=V2ZWB], Entity [id=3, afk=BTZW, name=V3B2A], Entity [id=4, afk=BTZW, name=V3B2B], Entity [id=5, afk=BTZW, name=V3B2C], Entity [id=6, afk=BTZW, name=V3B2D], Entity [id=7, afk=BTZW, name=V3B2E], Entity [id=8, afk=BTZW, name=V3B3A], Entity [id=9, afk=BTZW, name=V3B3B], Entity [id=10, afk=BTZW, name=V3B3C], Entity [id=11, afk=BTZW, name=VWA], Entity [id=12, afk=BTZW, name=VWB], Entity [id=13, afk=BTZW, name=VWC]]]]

For resolving entities I propose to create new class which can help you with this. For example:

classEntityResolver {

    private Map<Integer, Entity> entities;

    publicEntityResolver(EntitiesOwner[] owners) {
        entities = new HashMap<Integer, Entity>(owners.length);
        for (EntitiesOwner owner : owners) {
            for (Entity entity : owner.getEntities()) {
                entities.put(entity.getId(), entity);
            }
        }
    }

    public Entity getById(int id) {
        return entities.get(id);
    }
}

Simple usage:

EntityResolver resolver = new EntityResolver(owners);
System.out.println(resolver.getById(0).getName());
System.out.println(resolver.getById(13).getName());

Above program prints:

Bijz. trajecten zorg en welzijn
VWC

Solution 2:

By default, a list in JSON maps to an ArrayList in Java. There might be a way to deserialize the list to a HashMap directly, but even then that method would be very complicated. Why not just deserialize your JSON list to an ArrayList and do some post processing to obtain the HashMap? Something like this:

publicMap<Integer, String> listToMap(List<Object> list) {
    Map<Integer, String> map = newHashMap<>();

    for (Object obj : list) {
        // you might want to try-catch all casts, some data might be invalidMap<String, Object> elt = (Map<String, Object>) obj;

        Integer id = (Integer) elt.get("id");
        String name = (String) elt.get("name");
        map.put(id, name);
    }

    return map;
}

EDIT

I didn't make explicit how to obtain the list to feed to the method above. In the snippet below, I use the String json like you declared it in your question. For completeness, refer to the raw data binding from the Jackson documentation.

List<Object> inputData = new ObjectMapper().readValue(json, List.class);
Map<String, Object> inputMap = (Map<String, Object>) inputData.get(0);
List<Object> opleidingen = (List<Object>) inputMap.get("Opleidingen");
List<Object> klassen = (List<Object>) inputMap.get("Klassen");

Map<Integer, String> opleidingenMap = listToMap(opleidingen);
Map<Integer, String> klassenMap = listToMap(klassen);

Now you can use the two maps in the way you described:

opleidingenMap.get(25)

gives

"Zakelijke dienstverlening"

Note that this way you end up with a separate map for opleidingen and klassen. If you'd rather have all elements in one map, you could make such a map like:

Map<Integer, String> fullMap = newHashMap<>();
fullMap.putAll(opleidingenMap);
fullMap.putAll(klassen);

Note that this assumes that there is no opleiding with the same id as some klas.

Post a Comment for "Json To Hashmap (jackson)"