使用引号将 groovy 映射序列化为字符串 [英] Serializing groovy map to string with quotes

查看:15
本文介绍了使用引号将 groovy 映射序列化为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 groovy 映射持久化到文件中.我目前的尝试是写出字符串表示,然后读回它并在我准备再次使用它时调用 evaluate 以重新创建地图.

I'm trying to persist a groovy map to a file. My current attempt is to write the string representation out and then read it back in and call evaluate on it to recreate the map when I'm ready to use it again.

我遇到的问题是地图的 toString() 方法从元素的值中删除了重要的引号.当我的代码调用评估时,它会抱怨一个未知的标识符.

The problem I'm having is that the toString() method of the map removes vital quotes from the values of the elements. When my code calls evaluate, it complains about an unknown identifier.

这段代码演示了这个问题:

This code demonstrates the problem:

m = [a: 123, b: 'test']
print "orig: $m
"

s = m.toString()
print " str: $s
"

m2 = evaluate(s)
print " new: ${m2}
"

前两个打印语句几乎可以工作 -- 但是键 b 的值周围的引号不见了.它没有显示 [a: 123, b: 'test'],而是显示 [a: 123, b: test].

The first two print statements almost work -- but the quotes around the value for the key b are gone. Instead of showing [a: 123, b: 'test'], it shows [a: 123, b: test].

此时损坏已完成.evaluate 调用在尝试将 test 评估为标识符而不是字符串时会阻塞.

At this point the damage is done. The evaluate call chokes when it tries to evaluate test as an identifier and not a string.

那么,我的具体问题:

  1. 有没有更好的方法在 Groovy 中序列化/反序列化地图?
  2. 有没有办法用正确的引号生成地图的字符串表示?

推荐答案

Groovy 提供了 inspect() 方法返回一个对象作为可解析的字符串:

Groovy provides the inspect() method returns an object as a parseable string:

// serialize
def m = [a: 123, b: 'test']
def str = m.inspect()

// deserialize
m = Eval.me(str)

另一种将 groovy 映射序列化为可读字符串的方法是使用 JSON:

Another way to serialize a groovy map as a readable string is with JSON:

// serialize
import groovy.json.JsonBuilder
def m = [a: 123, b: 'test']
def builder = new JsonBuilder()
builder(m)
println builder.toString()

// deserialize
import groovy.json.JsonSlurper
def slurper = new JsonSlurper()
m = slurper.parseText('{"a": 123, "b": "test"}')

这篇关于使用引号将 groovy 映射序列化为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆