简体   繁体   中英

How to iterate a List<Map<String,String>> and add its key,values in a Java Object

I have a Java object which have four attributes, I want to set these attributes from result of List<Map<String,String>> .

Java class:

class Fruit{ 
    private String apple;
    private String banana;    
    private String mango;   
    private String orange;

    //getter and setters
}

I have a method that returns data in the form of List<Map<String, String>> :

[
  {"apple":"sweet","banana":"less sweet","mango":"more sweet","orange":"citric"},
  {"apple":"less sweet","banana":"more sweet","mango":" sweet","orange":"less citric"}
]

My task is to map these values to my Java class object so that I can return from my main method, something like List<Fruit> :

public List<Fruit> getfruits(){

    Fruit f=new Fruit();
    List<Map<String,String>> data=getdetails(returns List<Map<String,String>>)
    for(int i=0;i<data.size;i++){
        Map<String,String> map=data.get(i);

        //Now I want to iterate my map in a such way that it adds objects to my java class and return a list of Fruit object:
        //mapping to getter and setters of my Fruit class

        f.setApple(map.get("apple"));
        f.setMango(map.get("mango");
        f.setBanana(map.get("banana");
        f.setOrange(map.get("orange");

        //But I don't want to hardcode the values in getter and setter methods
    }
}

You can do this with help of ObjectMapper

       ObjectMapper mapper = new ObjectMapper();

List<Map<String,String>> dataMap = new ArrayList<>();

    String json = objectMapper.writeValueAsString(dataMap);

List<Fruit> fruits = mapper.readValue(json, new TypeReference<List<Fruit>>() {});

You can use Reflection. Directly or via Apache Commons BeanUtils ( PropertyUtils .get/setProperty) or via something else.

Maybe something like:

public List<Fruit> getFruits() {
     List<Fruit> fruits = new ArrayList<Fruit>();
     for (Map<String, String> m : data) {
           Fruit f = new Fruit();
           f.setApple(m.get(“apple”));
           f.setMango(m.get(“mango”));
           f.setBanana(m.get(“banana”));
           f.setOrange(m.get(“orange”));
           fruits.add(f);
     }
     return fruits;
}

Edit : Didn't see that you didn't want them hard coded, so you need to have a different way of setting your values. Perhaps make a set() method that has a parameter for what is being saved and the value.

Edit 2 : Why not just have one map variable in your Fruit class and just have a method to get and set based on keys?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM