直接看代码,环境为groovy1.8.6+jdk1.5.31,调试环境使用GroovyConsole
将Gson.jar放到groovy\lib目录里。
输出如下:
将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<user>对象 **/
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"]}