data class Person(val name: String="",val age:Int=0) { }
Java代码实现:
//json转List public static <T> java.util.List<T> getListFromJson(String json, Class<T[]> clazz) { try { T[] arr = new Gson().fromJson(json, clazz); return Arrays.asList(arr); } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] args) { String str = "[{"age":1,"name":"kongpf"},{"age":2,"name":"kongpf"},{"age":3,"name":"kongpf"},{"age":4,"name":"kongpf"},{"age":5,"name":"kongpf"},{"age":6,"name":"kongpf"},{"age":7,"name":"kongpf"},{"age":8,"name":"kongpf"},{"age":9,"name":"kongpf"},{"age":10,"name":"kongpf"}]"; java.util.List<Person> list = getListFromJson(str, Person[].class); list.forEach(person -> { System.out.println(person.toString()); }); }
kotlin代码实现:
//json转list fun <T> getListFromJson(json: String?, clazz: Class<Array<T>>): List<T>? { try { val arr: Array<T> = Gson().fromJson(json, clazz) return Arrays.asList(*arr) } catch (e: Exception) { e.printStackTrace() } return null } fun main() { var str="[{"age":1,"name":"kongpf"},{"age":2,"name":"kongpf"},{"age":3,"name":"kongpf"},{"age":4,"name":"kongpf"},{"age":5,"name":"kongpf"},{"age":6,"name":"kongpf"},{"age":7,"name":"kongpf"},{"age":8,"name":"kongpf"},{"age":9,"name":"kongpf"},{"age":10,"name":"kongpf"}]" var list= getListFromJson(str, Array<Person>::class.java) list?.forEach { println(it) } }