天天看點

groovy json操作1. 轉換成json2. json轉換成對象

1. 轉換成json

使用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"
        }
]
           

2. json轉換成對象

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)
}