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

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

问题描述

我试图将一个常规的地图保存到一个文件中。我目前的尝试是写出字符串表示,然后再读回来,并在它上面调用 evaluate 来重新创建地图,当我准备再次使用它时。



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



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

<$ p $ m = [a:123,b:'test']
printorig:$ m\\\


s = m.toString()
printstr:$ s\\\


m2 =评估(b)
打印新:$ {m2} \\\

前两个打印语句几乎可以工作 - 但键值 b 消失了。它不显示 [a:123,b:'test'] ,它显示 [a:123,b:test]



此时损坏已完成。 evaluate 当它尝试将 test 作为标识符而不是字符串时,调用扼流圈。



所以,我的具体问题是:


  1. 有没有更好的方法来序列化/反序列化地图Groovy?

  2. 有没有一种方法可以用正确的引号生成地图的字符串表示形式?


解决方案

)$ rel =noreferrer> inspect() 方法返回一个对象作为可解析的字符串:



< pre $ //序列化
def m = [a:123,b:'test']
def str = m.inspect()

//反序列化
m = Eval.me(str)

另一种序列化a groovy map是一个可读的字符串,带有JSON:

  //序列化
导入groovy.json.JsonBuilder
def m = [a:123,b:'test']
def bu ilder = new JsonBuilder()
builder(m)
println builder.toString()

//反序列化
导入groovy.json.JsonSlurper
def slurper = new JsonSlurper()
m = slurper.parseText('{a:123,b:test}')


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.

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\n"

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

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

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].

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

So, my specific questions:

  1. Is there a better way to serialize/de-serialize maps in Groovy?
  2. Is there a way to produce a string representation of a map with proper quotes?

解决方案

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)

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天全站免登陆