Groovy 序列化
本文链接:https://blog.csdn.net/feather_wch/article/details/131623398
JSON
class Person {
String name
Integer age
}
//对象转成json字符串
def list=[new Person(name:'jett',age:18),
new Person(name:'lance',age:18)]
println JsonOutput.toJson(list)
//对象转成json字符串: 格式化
def json=JsonOutput.toJson(list)
println JsonOutput.prettyPrint(json)
//json字符串转成对象
def jsonSluper=new JsonSlurper()
def object=jsonSluper.parse("[{\"age\":18,\"name\":\"jett\"},{\"age\":18,\"name\":\"lance\"}]".getBytes())
println object
def object2=jsonSluper.parse("[{\"abc\":\"jett\"}]".getBytes())
println object2.abc
XML
final String xml='''
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.jvm_demo_20200601">
<test>12345</test>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
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>
<activity android:name=".MainActivity2">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
'''
//解析XML数据
def xmlSluper=new XmlSlurper()
def result=xmlSluper.parseText(xml)
println result.@package
println result.test.text()
//读取有域名空间的节点
result.declareNamespace('android':'http://schemas.android.com/apk/res/android')
println result.application.@'android:allowBackup'
println result.application.activity[0].@'android:name'
println result.application.activity[1].@'android:name'
//遍历XML节点
result.application.activity.each{activity ->
println activity.@'android:name'
}
/**
* 生成XML格式数据
* <html>
* <title id='123',name='android'>xml生成
* <person></person>
* </title>
* <body name='java'>
* <activity id='001' class='MainActivity'>abc</activity>
* <activity id='002' class='SecActivity'>abc</activity>
* </body>
* </html>
*/
def sw=new StringWriter()
def xmlBuilder=new MarkupBuilder(sw)
xmlBuilder.html(){
title(id:'123',name:'android','xml生成'){
person()
}
body(name:'java'){
activity(id:'001',class:'MainActivity','abc')
activity(id:'002',class:'SecActivity','abc')
}
}
println sw