使用JsonOutput类可以直接将对象转换成Json字符串
示例:
Person.groovy
package objectorention
class Person {
String name
Integer age
def increaseAge(Integer years) {
this.name += years
}
def invokeMethod(String name, Object args) {
return "the methos is ${name}, the params is ${args}"
}
def methodMissing(String name, Object args){
return "the methos is ${name} is missing"
}
}
jsonstudy.groovy
package file
import groovy.json.JsonOutput
import objectorention.Person
def list = [new Person(name: 'John', age: 25),
new Person(name: 'Major', age: 26)]
println JsonOutput.toJson(list)
输出结果:
[{"age":25,"name":"John"},{"age":26,"name":"Major"}]
也可以直接输出带格式的json字符串,将代码修改如下
def list = [new Person(name: 'John', age: 25),
new Person(name: 'Major', age: 26)]
def json = JsonOutput.toJson(list)
println JsonOutput.prettyPrint(json)
输出结果:
[
{
"age": 25,
"name": "John"
},
{
"age": 26,
"name": "Major"
}
]
groovy使用JsonSlurper类可以进行Json解析
def jsonSlpuer = new JsonSlurper()
jsonSlpuer.parse()
也可以使用第三方类库进行json解析,以使用Gson为例,创建以src同级的libs目录,把Gson的jar包拷贝到该目录下,右键将jar包Add as Library。
json转换成Object例子
Person.groovy
package objectorention
class Person {
String name
Integer age
def increaseAge(Integer years) {
this.name += years
}
def invokeMethod(String name, Object args) {
return "the methos is ${name}, the params is ${args}"
}
def methodMissing(String name, Object args){
return "the methos is ${name} is missing"
}
}
jsonstudy.groovy
package file
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import objectorention.Person
def list = [new Person(name: 'John', age: 25),
new Person(name: 'Major', age: 26)]
def json = JsonOutput.toJson(list)
println JsonOutput.prettyPrint(json)
def jsonSlpuer = new JsonSlurper()
def list1 = jsonSlpuer.parseText(json)
println list1.getClass()
使用网络请求获取在线json
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import objectorention.Person
def reponse =
getNetworkData(
'http://baike.baidu.com/api/openapi/BaikeLemmaCardApi?scope=103&format=json&appid=379020&bk_key=%E5%85%B3%E9%94%AE%E5%AD%97&bk_length=600')
println reponse.data.head.name
def getNetworkData(String url) {
//发送http请求
def connection = new URL(url).openConnection()
connection.setRequestMethod('GET')
connection.connect()
def response = connection.content.text
//将json转化为实体对象
def jsonSluper = new JsonSlurper()
return jsonSluper.parseText(response)
}