Groovy語法學習(六)JSON、XML使用
阿新 • • 發佈:2019-02-17
groovy對於json和xml的生成和解析不需要額外匯入庫了,直接呼叫api使用。
一、JSON
(一) JSON字串建立
1.使用JsonBuilder類
JsonBuilder有call()方法傳入closure,所以可以接像下面這樣寫,相當於呼叫call方法。
def builder = new JsonBuilder()
builder{
name'jabamiYu'
age 12
}
assert builder.toString()=="{\"name\":\"jabamiYu\",\"age\":12}"
2.使用物件直接轉字串
class Franxx{
def name
def sex
}
def p =new Franxx(name:"zero two",sex:"female")
println new JsonBuilder(p)
println JsonOutput.toJson(p)
println JsonOutput.prettyPrint(JsonOutput.toJson(p))
結果:
{"sex":"female","name":"zero two"}
{"sex":"female","name":"zero two"}
{
"sex": "female" ,
"name": "zero two"
}
更多稍微複雜的用法,大家可以去參考對應幾個類註釋,註釋上都有例子。
二、XML
(一) 解析xml
使用安卓的Manifest檔案
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ty">
<application
android:allowBackup ="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<meta-data android:name="hello" android:value="1"/>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
解析
def parser = new XmlParser().parse(new File("AndroidManifest.xml"))
//建立名稱空間
def ns = new Namespace('http://schemas.android.com/apk/res/android','android')
Node nodeactivity = parser.application[0].activity[0]
println nodeactivity.attributes()[ns.name]
//獲得application節點
Node node = parser.application[0]
//NodeList
Node meta = node.'meta-data'[0]
node.remove(meta)
node.appendNode('meta-data',[(ns.name):'a',(ns.value):'b',(ns.hh):'hh'])
new XmlNodePrinter(new PrintWriter(new File("replace.xml"))).print(parser)
replace.xml
<manifest package="com.example.ty">
<application android:allowBackup="true" xmlns:android="http://schemas.android.com/apk/res/android" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data android:name="a" android:value="b" android:hh="hh"/>
</application>
</manifest>
(二) 生成xml
def fw = new FileWriter(new File("normal.xml"))
def builder = new MarkupBuilder(fw)
builder.html{
mkp.comment("test")
head("hello",m:'a'){
title("com.jabamiYu")
}
body{
}
}
def sb = new StreamingMarkupBuilder()
sb.encoding = 'UTF-8'
def closure = {
mkp.xmlDeclaration()
html{
head(id:1){
}
}
}
def sw = sb.bind(closure)
println sw.toString()
結果:
normal.xml檔案
<html><!-- test -->
<head m='a'>hello
<title>com.jabamiYu</title>
</head>
<body />
</html>
列印:
<?xml version='1.0' encoding='UTF-8'?>
<html><head id='1'></head></html>
只總結了一些簡單用法,更加複雜的用法同樣可以通過檢視註釋。