javaobjectarraylistname-value

How to convert Object to NameValuePair ArrayList in Java?


Lets say we have an object of Class Person with all String parameters :

Class Person {

 String name;
 String email;

}

Person p = new Person();
p.name = "ABC";
p.email = "abc@xyz.com";

How do we convert object p to ArrayList of NameValue Pair :

Output should be a ArrayList<NameValuePair> with following content :

"name" : "ABC" 
"email" : "abc@xyz.com"

Solution

  • Here you are .. it's a dynamic so you can use it for any object .. I'm using the reflection

    public static void main(String[] args) {
    
        Person person = new Person("Ali", "a@c.o");
        try {
            System.out.println(getObjectNameValuePairs(person));
    
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
    }
    
    public static ArrayList<NameValuePair> getObjectNameValuePairs(Object obj) throws IllegalArgumentException, IllegalAccessException {
        ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();
        for (Field field : obj.getClass().getDeclaredFields()) {
            field.setAccessible(true); // if you want to modify private fields
            NameValuePair nameValuePair = new NameValuePair();
            nameValuePair.setName(field.getName());
            nameValuePair.setValue(field.get(obj));
            list.add(nameValuePair);
        }
        return list;
    }
    

    this output will be

    [[name:Ali], [email:a@c.o]]
    

    considering that the NameValuePair implementation is

    public class NameValuePair {
    private String name;
    private Object value;
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public Object getValue() {
        return value;
    }
    
    public void setValue(Object value) {
        this.value = value;
    }
    
    @Override
    public String toString() {
        return "["+ name + ":" + value + "]";
    }
    

    }

    I hope this could help!