将Gson.jar放到groovy\lib目录里。
import com.google.gson.Gson class Test { static main(args){ String jsonTxt = '[{"name":"老张头", "age":66, "phone":["13021131", "15010921"]},{"name":"老李头", "age":86, "phone":["15010353", "13161244"]}]' Gson gson = new Gson() /** 将JSON格式字符串转换成List对象 **/ List users = gson.fromJson(jsonTxt, List.class) println users /********************************************************/ String jsonTxt1 = '{"name":"老张头", "age":66, "phone":["13021131", "15010921"]}' /** 将JSON格式字符串转换成JavaBean对象 **/ User user = gson.fromJson(jsonTxt1, User.class) println user /** 将JavaBean对象转换为JSON格式字符串 **/ String jsonRetString = gson.toJson(user) println jsonRetString } } private class User { String name int age List phone }
输出如下:
[[name:老张头, age:66.0, phone:[13021131, 15010921]], [name:老李头, age:86.0, phone:[15010353, 13161244]]] User@1192efd {"name":"老张头","age":66,"phone":["13021131","15010921"]}