当前位置:网站首页>Groovy XML JSON
Groovy XML JSON
2022-08-08 15:39:00 【bobo洁厕灵】
XML是一种便携的开放源代码语言,允许程序员开发可以被其他应用程序读取的应用程序,而不管操作系统和/或开发语言。这是用于在应用程序之间交换数据的最常用的语言之一
XML是什么?
可扩展标记语言XML是一种非常类似于HTML或SGML的标记语言。这是万维网联盟推荐的,可作为开放标准。XML对于跟踪少量到中等数据量而不需要基于SQL的骨干非常有用。
Groovy中的XML支持
XML标记构建器 - Groovy支持基于树的标记生成器BuilderSupport,它可以被子类化以生成各种树结构对象表示。通常,这些构建器用于表示XML标记,HTML标记。 Groovy的标记生成器捕获对伪方法的调用,并将它们转换为树结构的元素或节点。这些伪方法的参数被视为节点的属性。作为方法调用一部分的闭包被视为生成的树节点的嵌套子内容。
XML解析器 - Groovy XmlParser类使用一个简单的模型来将XML文档解析为Node实例的树。每个节点都有XML元素的名称,元素的属性和对任何子节点的引用。这个模型足够用于大多数简单的XML处理。
这是一个xml示例文件
<collection shelf = "New Arrivals">
<movie title = "Enemy Behind">
<type>War, Thriller</type>
<format>DVD</format>
<year>2003</year>
<rating>PG</rating>
<stars>10</stars>
<description>Talk about a US-Japan war</description>
</movie>
<movie title = "Transformers">
<type>Anime, Science Fiction</type>
<format>DVD</format>
<year>1989</year>
<rating>R</rating>
<stars>8</stars>
<description>A schientific fiction</description>
</movie>
<movie title = "Trigun">
<type>Anime, Action</type>
<format>DVD</format>
<year>1986</year>
<rating>PG</rating>
<stars>10</stars>
<description>Vash the Stam pede!</description>
</movie>
<movie title = "Ishtar">
<type>Comedy</type>
<format>VHS</format>
<year>1987</year>
<rating>PG</rating>
<stars>2</stars>
<description>Viewable boredom </description>
</movie>
</collection>
XML标记生成器
MarkupBuilder用于构造整个XML文档。通过首先创建XML文档类的对象来创建XML文档。一旦创建了对象,可以调用伪方法来创建XML文档的各种元素。
import groovy.xml.MarkupBuilder
class Example {
static void main(String[] args) {
def mB = new MarkupBuilder()
// Compose the builder
//mb.collection这是一个标记生成器,用于创建<collection> </ collection>的头XML标签
mB.collection(shelf : 'New Arrivals') {
//movie(title : 'Enemy Behind') -这些伪方法使用此方法创建带有值的标记的子标记。通过指定一个名为title的值,这实际上表示需要为该元素创建一个属性。
movie(title : 'Enemy Behind')
type('War, Thriller')
format('DVD')
year('2003')
rating('PG')
stars(10)
description('Talk about a US-Japan war')
}
}
}
如果创建整个xml文档,
需要执行以下操作。
- 需要创建映射条目以存储元素的不同值。
- 对于地图的每个元素,我们将值分配给每个元素。
import groovy.xml.MarkupBuilder
class Example {
static void main(String[] args) {
def mp = [1 : ['Enemy Behind', 'War, Thriller','DVD','2003',
'PG', '10','Talk about a US-Japan war'],
2 : ['Transformers','Anime, Science Fiction','DVD','1989',
'R', '8','A scientific fiction'],
3 : ['Trigun','Anime, Action','DVD','1986',
'PG', '10','Vash the Stam pede'],
4 : ['Ishtar','Comedy','VHS','1987', 'PG',
'2','Viewable boredom ']]
def mB = new MarkupBuilder()
// Compose the builder
def MOVIEDB = mB.collection('shelf': 'New Arrivals') {
mp.each {
sd ->
mB.movie('title': sd.value[0]) {
type(sd.value[1])
format(sd.value[2])
year(sd.value[3])
rating(sd.value[4])
stars(sd.value[4])
description(sd.value[5])
}
}
}
}
}
XML解析
Groovy XmlParser类使用一个简单的模型来将XML文档解析为Node实例的树。每个节点都有XML元素的名称,元素的属性和对任何子节点的引用。这个模型足够用于大多数简单的XML处理。
将movies.xml文件中的数据按照要求向用户输出
import groovy.xml.MarkupBuilder
import groovy.util.*
class Example {
static void main(String[] args) {
def parser = new XmlParser()
def doc = parser.parse("D:Movies.xml");
doc.movie.each{
bk->
print("Movie Name:")
println "${bk['@title']}"
print("Movie Type:")
println "${bk.type[0].text()}"
print("Movie Format:")
println "${bk.format[0].text()}"
print("Movie year:")
println "${bk.year[0].text()}"
print("Movie rating:")
println "${bk.rating[0].text()}"
print("Movie stars:")
println "${bk.stars[0].text()}"
print("Movie description:")
println "${bk.description[0].text()}"
println("*******************************")
}
}
}
Groovy JSON
使用JsonSlurper解析数据
JsonSlurper是一个将JSON文本或阅读器内容解析为Groovy数据结构的类,如地图,列表和原始类型,如Integer,Double,Boolean和String。
示例是使用http模块从Web服务器获取JSON数据。对于这种类型的遍历,最好的选择是将解析器类型设置为JsonParserLax变体。
http.request( GET, TEXT ) {
headers.Accept = 'application/json'
headers.'User-Agent' = USER_AGENT
response.success = {
res, rd ->
def jsonText = rd.text
//Setting the parser type to JsonParserLax
def parser = new JsonSlurper().setType(JsonParserType.LAX)
def jsonResp = parser.parseText(jsonText)
}
}
文本解析
import groovy.json.JsonSlurper
class Example {
static void main(String[] args) {
def jsonSlurper = new JsonSlurper()
//使用JsonSlurper类的parseText函数来解析一些JSON文本
def object = jsonSlurper.parseText('{ "name": "John", "ID" : "1"}')
//获取对象时,看到实际上可以通过键访问JSON字符串中的值
println(object.name);
println(object.ID);
}
}
解析整数列表
import groovy.json.JsonSlurper
class Example {
static void main(String[] args) {
def jsonSlurper = new JsonSlurper()
Object lst = jsonSlurper.parseText('{ "List": [2, 3, 4, 5] }')
lst.each { println it }
}
}
解析基本数据类型列表
JSON解析器还支持字符串,数字,对象,true,false和null的原始数据类型。 JsonSlurper类将这些JSON类型转换为相应的Groovy类型。
import groovy.json.JsonSlurper
class Example {
static void main(String[] args) {
def jsonSlurper = new JsonSlurper()
def obj = jsonSlurper.parseText ''' {"Integer": 12, "fraction": 12.55, "double": 12e13}'''
println(obj.Integer);
println(obj.fraction);
println(obj.double);
}
}
JSON OUTPUT
在json中打印输出,使用JsonOutput方法来完成。此方法负责将Groovy对象序列化为JSON字符串。
import groovy.json.JsonOutput
class Example {
static void main(String[] args) {
def output = JsonOutput.toJson([name: 'John', ID: 1])
println(output);
}
}
JsonOutput也可以用于普通的旧Groovy对象
import groovy.json.JsonOutput
class Example {
static void main(String[] args) {
def output = JsonOutput.toJson([ new Student(name: 'John',ID:1),
new Student(name: 'Mark',ID:2)])
println(output);
}
}
class Student {
String name
int ID;
}
边栏推荐
猜你喜欢
【云原生】-MySQL压测神器HammerDB的部署及使用
[Unity Starter Plan] Making RubyAdventure02 - Handling Tile Maps & Collision
Install Update(Patches) on ESXi
Take you to play with the "Super Cup" ECS features and experiment on the pit [HUAWEI CLOUD is simple and far]
[Unity entry plan] Unity instance - how to protect data members through encapsulation in C#
Thoroughly understand the volatile keyword and application scenarios, and it is a must for interviews, and Xiaobai can understand it!
基于LEAP模型的能源环境发展、碳排放建模预测及不确定性分析
Create a 2D array
Power BI简介
761. 特殊的二进制序列 : 经典构造题
随机推荐
【kali-权限提升】(4.2.5)社会工程学工具包:PowerShell攻击向量(防报毒)
Thread local storage ThreadLocal
Kubernetes-Basics-Common Commands
Common regularization methods in deep learning (Regularization) and detailed explanation of WeightDecay parameters in optimizers
Thoroughly understand the volatile keyword and application scenarios, and it is a must for interviews, and Xiaobai can understand it!
什么是低代码开发?大家都真的看好低代码开发吗?
Synergistic authors open source throttling, 2022 trend of technology foresight (asynchronous programming/container technology)
幂等性~~
What is low-code development?Is everyone really optimistic about low-code development?
All volunteers V853 chip Tina RTSP environment set up
企业开发小程序有什么优势?为什么要开发小程序?
hdu2475 Box
一文读懂字节跳动“埋点验证平台”
web-sql注入
Chat with wine and chat, build an asynchronous non-blocking (aioredis) real-time (websocket) communication chat system based on Vue3.0+Tornado6.1+Redis publish-subscribe (pubsub) mode
一文搞懂│XSS攻击、SQL注入、CSRF攻击、DDOS攻击、DNS劫持
大佬们,这个测试demo只能获取到全量数据,不能获取增量,我的mysql 已经开启了row模式的bi
想去银行测试?那这套题目你必须要会
快速排序(C语言版)
codeforces 444C DZY Loves Colors