Groovy中的json操作

json ->object

1
2
3
4
5
6
final String myJson ='''
{"code":200,"body":{"search_result":[{"id":"1393","name":"东京食尸鬼漫画","cover_url":"http://img.1whour.com/xpic/东京食尸鬼.jpg","other_1":"","other_2":""},{"id":"2402","name":"东京都立咒术学校漫画","cover_url":"http://img.1whour.com/xpic/东京都立咒术学校.jpg","other_1":"","other_2":""},{"id":"1107","name":"大东京玩具箱漫画","cover_url":"http://img.1whour.com/xpic/大东京玩具箱.jpg","other_1":"","other_2":""},{"id":"2026","name":"东京小红帽漫画","cover_url":"http://img.1whour.com/xpic/东京小红帽.jpg","other_1":"","other_2":""},{"id":"879","name":"东京ESP漫画","cover_url":"http://img.1whour.com/xpic/djESP.jpg","other_1":"","other_2":""},{"id":"2064","name":"东京暗鸦SwordOfSong漫画","cover_url":"http://img.1whour.com/xpic/东京暗鸦Sword.jpg","other_1":"","other_2":""},{"id":"943","name":"东京乌鸦漫画","cover_url":"http://img.1whour.com/xpic/东京乌鸦.jpg","other_1":"","other_2":""},{"id":"1954","name":"东京奇迹少年漫画","cover_url":"http://img.1whour.com/xpic/东京奇迹少年.jpg","other_1":"","other_2":""},{"id":"1106","name":"东京玩具箱漫画","cover_url":"http://img.1whour.com/xpic/东京玩具箱.jpg","other_1":"","other_2":""},{"id":"430","name":"东京MewMew漫画","cover_url":"http://img.1whour.com/xpic/0djmm.jpg","other_1":"","other_2":""},{"id":"358","name":"东京80年代漫画","cover_url":"http://img.1whour.com/xpic/363.jpg","other_1":"","other_2":""}]}}
'''
def jsonSluper = new JsonSlurper()
def object = jsonSluper.parseText(myJson)
println object.body.search_result[0]

[id:1393, name:东京食尸鬼漫画, cover_url:http://img.1whour.com/xpic/东京食尸鬼.jpg, other_1:, other_2:]
东京食尸鬼漫画

object -> json

1
2
3
4
5
def cars = [new Car(name: 'qihu',money: 2000),
new Car(name: 'qq',money: 1000),
new Car(name: 'haha',money: 3000)]
def json = JsonOutput.toJson(cars)
println JsonOutput.prettyPrint(json)

[{“money”:2000,”name”:”qihu”},{“money”:1000,”name”:”qq”},{“money”:3000,”name”:”haha”}]

[
​ {
​ “money”: 2000,
​ “name”: “qihu”
​ },
​ {
​ “money”: 1000,
​ “name”: “qq”
​ },
​ {
​ “money”: 3000,
​ “name”: “haha”
​ }
]