0

I have a code to parse a huge JSON:

static <T> List<T> parseJSON(String json) {
   Map<String, T> result = jsonSlurper.parseText(json)
   List<T> list = result.result
   return list
}

the String json = {result:[{obj1},{obj2}....]}

I am getting a proper List at the end with the variable list but in Java when I get the value it throws an exception java.lang.ClassCastException: groovy.json.internal.LazyMap cannot be cast to {MyPOJO}

here is how I receive the data

List<MYClass> list = MyClass.parseJSON(someString);
for(MyClass i : list) {
  System.out.println(i.someValue());
}

how can I resolve this?

1 Answers1

0

Your generic does not make much sense. When having such json string in your question, parseJSON always return a list of groovy.json.internal.LazyMap. You have to convert explicitly from LazyMap to MyClass. Otherwise just a cast exception.

Here is my code:

class MyClass {
    MyClass(Map map) {
        this.a = map.a as int
        this.b = map.b
    }
    int a
    String b

}

    List<Map> jSON = parseJSON("""{"result":[{"a":2,"b":"b"},{"a":2,"b":"b"}]}""")
    for (def item in jSON) {
        def myClass = new MyClass(item)
        println myClass.a
    }
aristotll
  • 8,694
  • 6
  • 33
  • 53