Saurabh Gaur
Saurabh Gaur

Reputation: 23805

How to convert list of maps to list of objects if list of maps has extra keys

My question is almost similar to How to convert list of maps to list of objects.

But the problem is now, I have list of maps where maps contains some extra keys which is not present in my Pojo class as property like as below :-

List list = [
    [param1: "a", param2: ["a","b","c"], param3:[a:"a",b:"b",c:"c"], param4:true, param5:1, param6: "pamra6",param7: "pamra7"],
    [param1: "b", param2: ["d","e","f"], param3:[d:"d",e:"e",f:"f"], param4:false, param5:2, param6: "pamra6",param7: "pamra7"]
]

In this list two extra keys param6, param7 included where this is not exist in Pojo class, because in my scenario I'm considering only those property which present in the Pojo, I can't increase extra property in the Pojo class.

So when I'm going to convert this list of maps to list of objects as below :-

list.collect { new Pojo(it) }

it's throwing an error as :-

groovy.lang.MissingPropertyException: No such property: param6 for class: Pojo

Which is absolutely correct, but when I'm converting like below :-

list.collect { it as  Pojo } 

or

list*.asType(Pojo)

It's not throwing any error but when we going to get values like this :-

.each { pojo ->

  pojo.param1
  ------------
  ------------
}

Couldn't found any of these value. all values found as null.

When I'm examine converted list of objects using .dump(), it converted as Pojo1_groovyProxy like as proxy object..

So my question is, how to convert in this situation???

Upvotes: 2

Views: 230

Answers (2)

Saurabh Gaur
Saurabh Gaur

Reputation: 23805

After Michael Easter and tim_yates suggestion, achieved this using as below :-

class Pojo {
 def param1
 def param2
 def param3
 def param4
 def param5

def static build(def map) {
    new Pojo(map.findAll { k, v -> k in Pojo.metaClass.properties*.name})
  }
}

def newList = list.collect { Pojo.build(it) }

Thanks for giving me big hint..:)

Upvotes: 0

Michael Easter
Michael Easter

Reputation: 24468

Here is one way to do it (which attempts to be resilient if param6 were later added to the class):

(edit: much cleaner, thanks to tim_yates)

class Pojo {
    def param1
    def param2
    def param3
    def param4
    def param5

    def static build(def map) {
        def fields = Pojo.declaredFields.findAll { !it.synthetic }*.name
        def keys = map.keySet().findAll { it in fields }
        def subMap = map.subMap(keys)
        new Pojo(subMap)
    }
}


def newList = list.collect { Pojo.build(it) }

Upvotes: 1

Related Questions