Groovy数据解析
一、json解析
//groovy中也可导入gson、fastJson等json解析库,与java中一致
//但是groovy中提供了使用起来更加简洁的方式
class Person {
String name
Integer age
}
def personList = [new Person(name: 'java', age: 28), new Person(name: 'groovy', age: 6)]
//将对象解析成json字符串
def result = JsonOutput.toJson(personList)
println result //[{"age":28,"name":"java"},{"age":6,"name":"groovy"}]
println JsonOutput.prettyPrint(result) //格式化输出
/**
[
{
"age": 28,
"name": "java"
},
{
"age": 6,
"namgovy"
}
]
*/
//将json字符串传化为对象
def jsonSlurper = new JsonSlurper()
def objectResult = (ArrayList) jsonSlurper.parseText(result)
Person p = objectResult[0]
println "the name is $p.name,the age is $p.age" //输出结果:the name is java,the age is 28
def getNetWorkData(String url) {
//发送http请求(此处用原生的,也可导入okHttp库进行网络操作)
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection()
connection.setConnectTimeout(10000)
connection.setRequestMethod('GET')
connection.connect()
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))
StringBuffer stringBuffer = new StringBuffer()
String json = ""
while ((json = bufferedReader.readLine()) != null) {
stringBuffer.append(json)
}
String rsp = new String(stringBuffer.toString().getBytes(), "UTF-8")
//解析
def jsonSlurper = new JsonSlurper()
return jsonSlurper.parseText(rsp)
}
/*
{"data":[{"desc":"一起来做个App吧","id":10,"imagePath":"http://www.wanandroid.com/blogimgs/50c115c2-cf6c-4802-aa7b-a4334de444cd.png","isVisible":1,"order":2,"title":"一起来做个App吧","type":0,"url":"http://www.wanandroid.com/blog/show/2"},{"desc":"","id":4,"imagePath":"http://www.wanandroid.com/blogimgs/ab17e8f9-6b79-450b-8079-0f2287eb6f0f.png","isVisible":1,"order":0,"title":"看看别人的面经,搞定面试~","type":1,"url":"http://www.wanandroid.com/article/list/0?cid=73"},{"desc":"","id":3,"imagePath":"http://www.wanandroid.com/blogimgs/fb0ea461-e00a-482b-814f-4faca5761427.png","isVisible":1,"order":1,"title":"兄弟,要不要挑个项目学习下?","type":1,"url":"http://www.wanandroid.com/project"},{"desc":"","id":6,"imagePath":"http://www.wanandroid.com/blogimgs/62c1bd68-b5f3-4a3c-a649-7ca8c7dfabe6.png","isVisible":1,"order":1,"title":"我们新增了一个常用导航Tab~","type":1,"url":"http://www.wanandroid.com/navi"},{"desc":"","id":2,"imagePath":"http://www.wanandroid.com/blogimgs/90cf8c40-9489-4f9d-8936-02c9ebae31f0.png","isVisible":1,"order":2,"title":"JSON工具","type":1,"url":"http://www.wanandroid.com/tools/bejson"},{"desc":"","id":5,"imagePath":"http://www.wanandroid.com/blogimgs/acc23063-1884-4925-bdf8-0b0364a7243e.png","isVisible":1,"order":3,"title":"微信文章合集","type":1,"url":"http://www.wanandroid.com/blog/show/6"}],"errorCode":0,"errorMsg":""}
*/
class Root {
List data
int errorCode
String errorMsg
class Data {
String desc
int id
String imagePath
int isVisible
int order
String title
int type
String url
}
}
Root root = getNetWorkData("http://www.wanandroid.com/banner/json")
println root.data[0].imagePath //输出结果:http://www.wanandroid.com/blogimgs/50c115c2-cf6c-4802-aa7b-a4334de444cd.png
//以上是类似java的做法,而在Groovy中,不需要写实体类,可直接使用里面的字段
def response = getNetWorkData("http://www.wanandroid.com/banner/json")
println response.data[0].imagePath //输出结果:http://www.wanandroid.com/blogimgs/50c115c2-cf6c-4802-aa7b-a4334de444cd.png
二、xml解析
- groovy解析xml数据
def xmlStr = '''
Android组件化架构
苍王
Android 插件化开发指南
包建强
Android开发艺术探索
任玉刚
Android源码设计模式2
何红辉
Vue从入门到精通
李刚
'''
//开始解析
def xmlSlurper = new XmlSlurper()
def response = xmlSlurper.parseText(xmlStr) //解析出来的即为根节点
//输出节点中对应节点的值
println response.value.books[0].book[1].title.text() //Android 插件化开发指南
//输出节点中属性的值,直接使用@
println response.value.books[0].book[1].@id //2
//遍历
def list = []
response.value.books.each { books ->
//再对books中的book节点遍历
books.book.each { book ->
def author = book.author.text()
if ('任玉刚' == author) {
list.add(book.title.text())
}
}
}
println list.toListString() // [Android开发艺术探索]
//groovy提供了另外的遍历xml方法
//深度遍历
def list2 = []
response.depthFirst().findAll { book ->
if ('任玉刚' == book.author.text()){
list2.add(book.title.text())
return true
}
}
println list2.toListString() //[Android开发艺术探索]
def titles = response.depthFirst().findAll { book ->
'任玉刚' == book.author.text()
}.collect { book->
book.title.text()
}
println titles.toListString() //[Android开发艺术探索]
//广度遍历
def titles2 = response.value.books.children().findAll { node ->
('2'.compareTo((node.@id).toString())) < 0
}.collect { book ->
book.title.text()
}
println titles2 //[Android开发艺术探索, Android源码设计模式2]
- groovy创建xml数据
def sw = new StringWriter()
//用来生成xml
def xmlBuilder = new MarkupBuilder(sw)
//创建根节点response并且添加属性version_api
xmlBuilder.response(version_api: '2.0') {
//在response中创建value节点
value() {
//在value中创建books节点
books(id: '1', classification: 'android') {
//在books节点中创建book节点
book(available: '20', id: '1') {
//创建title节点,(value为Android组件化架构,即title.text()的值)
title('Android组件化架构') {}
//创建author节点
author(id: '1', '苍王') {}
}
//第二个book节点
book(available: '14', id: '2') {
title('Android插件化开发指南') {}
author(id: '2', '包建强') {}
}
//第三个book节点
book(available: '13', id: '3') {
title('Android开发艺术探索') {}
author(id: '3', '任玉刚') {}
}
//第四个book节点
book(available: '5', id: '4') {
title('Android源码设计模式2') {}
author(id: '4', '何红辉') {}
}
}
//创建第二个books节点
books(id: '2', classification: 'web') {
//在books节点中创建book节点
book(available: '10', id: '1') {
//创建title节点,(value为Android组件化架构,即title.text()的值)
title('Vue从入门到精通') {}
//创建author节点
author(id: '4', '李刚') {}
}
}
}
}
println sw //输出结果
'''
Android组件化架构
苍王
Android 插件化开发指南
包建强
Android开发艺术探索
任玉刚
Android源码设计模式2
何红辉
Vue从入门到精通
李刚
'''
//模仿服务器中已有的数据
class Response {
String version_api
Value value
}
class Value {
def books = [new Books(id: '1', classification: 'android', book: [new Book(available: '20', id: '1', title: new Title(value: 'Android组件化架构'), author: new Author(id: '1', value: '苍王'))
, new Book(available: '14', id: '2', title: new Title(value: 'Android插件化开发指南'), author: new Author(id: '2', value: '包建强'))
, new Book(available: '13', id: '3', title: new Title(value: 'Android开发艺术探索'), author: new Author(id: '3', value: '任玉刚'))
, new Book(available: '5', id: '4', title: new Title(value: 'Android源码设计模式2'), author: new Author(id: '4', value: '何红辉'))]),
new Books(id: '2', classification: 'web', book: [new Book(available: '10', id: '1', title: new Title(value: 'Vue从入门到精通'), author: new Author(id: '4', value: '李刚'))])]
}
class Books {
String id
String classification
ArrayList book
}
class Book {
String available
String id
Title title
Author author
}
class Title {
def value
}
class Author {
def id
def value
}
def sw2 = new StringWriter()
//用来生成xml
def xmlBuilder2 = new MarkupBuilder(sw2)
//初始化数据,假设是从服务器中获取的数据
def response2 = new Response(version_api: '2.0', value: new Value())
xmlBuilder2.response(version_api: "$response2.version_api") {
value() {
response2.value.books.each { booksNode ->
//循环创建books节点
books(id: booksNode.id, classification: booksNode.classification) {
booksNode.book.each { bookNode ->
//循环创建book节点
book(available: bookNode.available, id: bookNode.id) {
title("$bookNode.title.value")
author(id: "$bookNode.author.id", "$bookNode.title.value")
}
}
}
}
}
}
println sw2 //输出结果
'''
Android组件化架构
Android组件化架构
Android插件化开发指南
Android插件化开发指南
Android开发艺术探索
Android开发艺术探索
Android源码设计模式2
Android源码设计模式2
Vue从入门到精通
Vue从入门到精通
'''