1

I have a HashMap of about 300 Key/String Value pairs and a POJO with about 12 string attributes where the names match the key names.

I would like to know how to get the HashMap values into the POJO?

I made this start which uses relfection and a loop but wasn't sure how to dynamically construct the setter method name, and apparently reflection is a bad idea anyway...but FWIW:

    public void writeToFile(Map<String, String> currentSale) throws IOException {

    SaleExport saleExport = new SaleExport();

    Field[] fields = saleExport.getClass().getDeclaredFields();

       for (Field field : fields ) {
        System.out.println(field.getName());
        saleExport.set +field(saleExport.get(field));

I have used map struct once before but it does not appear to support HashMaps.

UPDATE

This answer looks similar to what I want to do but gave a stack error on fields that didn't map:

Exception in thread "Thread-2" java.lang.IllegalArgumentException: Unrecognized field "Physical" (class com.SaleExport), not marked as ignorable (6 known properties: "date", "city", "surname", "streetName", "salesNo", "salesSurname"])
 at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.SalesExport["Physical"])
    at com.fasterxml.jackson.databind.ObjectMapper._convert(ObjectMapper.java:3738)
    at com.fasterxml.jackson.databind.ObjectMapper.convertValue(ObjectMapper.java:3656)
    at com.CSVExport.writeToFile(CSVExport.java:20)
    at com.JFrameTest.writefiletoDB(JFrameTest.java:135)
    at com.JFrameTest$FileWorkerThread.run(JFrameTest.java:947)

To ignore the errors I tried :

mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

But then nothing got mapped.

Al Grant
  • 2,102
  • 1
  • 26
  • 49

5 Answers5

1

If i have understood your question correctly - you want to put the value of map into the member variable of the Pojo based on key.

Try below approach.

Main Class as follows

package org.anuj.collections.map;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class ConverMapToPojo {

    public static void main(String[] args) {
        Map<String, String> map = getMap();
        Set<String> keySet = map.keySet();

        String fieldName = null;
        Pojo pojo = new Pojo();
        Field[] field = Pojo.class.getDeclaredFields();

        for (Field f : field) {
            fieldName = f.getName();
            if (keySet.contains(fieldName)) {
                pojo = setField(fieldName, map.get(fieldName), pojo);
            }
        }
        System.out.println("fName = " + pojo.getfName());
        System.out.println("lName = " + pojo.getlName());
    }

    private static Pojo setField(String fieldName, String value, Pojo pojo) {
        switch (fieldName) {
        case "fName":
            pojo.setfName(value);
            break;
        case "lName":
            pojo.setlName(value);
            break;
        }
        return pojo;
    }

    private static Map<String, String> getMap() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("fName", "stack");
        map.put("lName", "overflow");
        return map;
    }
}

Pojo Class as follows -

public class Pojo {

    private String fName;
    private String lName;

    public String getfName() {
        return fName;
    }

    public void setfName(String fName) {
        this.fName = fName;
    }

    public String getlName() {
        return lName;
    }

    public void setlName(String lName) {
        this.lName = lName;
    }
}

The Result comes out to be

fName = stack lName = overflow

0

Try using Dozer mapping to map HashMap to POJO.You can look at MapStruct too.

Ankur Srivastava
  • 855
  • 9
  • 10
0

Hi I don't know if it's a good Idea but you could convert your map to a json and convert json to your POJO. You could use gson.

ScorprocS
  • 287
  • 3
  • 14
0

You can inject something in a pojo member variable through e.g. a method like this. I do not say that it is a good way to do this, but it can be done like this.

import java.lang.reflect.Field;
import java.util.HashMap;

/**
 * @author Ivo Woltring
 */
public class HashMapKeyStuff {

    /**
     * The most simple cdi like method.
     *
     * @param injectable the object you want to inject something in
     * @param fieldname  the fieldname to inject to
     * @param value      the value to assign to the fieldname
     */
    public static void injectField(final Object injectable, final String fieldname, final Object value) {
        try {
            final Field field = injectable.getClass()
                    .getDeclaredField(fieldname);
            final boolean origionalValue = field.isAccessible();
            field.setAccessible(true);
            field.set(injectable, value);
            field.setAccessible(origionalValue);
        } catch (final NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    private void doIt() {
        HashMap<String, String> foo = new HashMap<>();
        foo.put("hello", "world");
        foo.put("message", "You are great");

        MyPOJO pojo = new MyPOJO();
        for (final String key : foo.keySet()) {
            injectField(pojo, key, foo.get(key));
        }
        System.out.println("pojo = " + pojo);
    }

    public static void main(String[] args) {
        new HashMapKeyStuff().doIt();
    }

}

class MyPOJO {
    private String hello;
    private String message;

    public String getHello() {
        return this.hello;
    }


    public String getMessage() {
        return this.message;
    }

    @Override
    public String toString() {
        return "MyPOJO{" +
                "hello='" + hello + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}
Ivonet
  • 2,492
  • 2
  • 15
  • 28
0

I think you had the right idea in your code. I understand your POJO to contain only a subset of the fields represented in the HashMap, so you just iterate through the fields, populating them from the HashMap as you find them.

public SaleExport toSaleExport(Map<String,String> currentSale) {
    SaleExport saleExport=new SaleExport();
    Field[] fields=SaleExport.class.getDeclaredFields();
    for (Field field : fields) {
        String name=field.getName();
        if (currentSale.containsKey(name)) {
            field.set(saleExport, currentSale.get(name));
        }
    }
    return saleExport;
}
phatfingers
  • 9,770
  • 3
  • 30
  • 44