【问题标题】:Problem serializing hashmap with snakeyaml in groovy在groovy中使用snakeyaml序列化hashmap的问题
【发布时间】:2018-10-23 13:32:11
【问题描述】:

问题是当我尝试使用snakeyaml 序列化数据时,它会出现格式错误,但是当我对jsonslurper 执行相同操作时,一切都已完美格式化。

地图是这样的

gateway_splunky:[appToken:samplekey14124fggfs], MySpaceCredentials:[credentials:[samplekey352453sdffgsdfs, dasklkldsakadsp32525902j5, j6klj65kj45kkj45h, 3hjhjk3h34kjh34k34]]

序列化后

yamlOutput = new Yaml().dump(map)

等于

gateway_splunky: {appToken: samplekey14124fggfs}

MySpaceCredentials:

  credentials: [samplekey352453sdffgsdfs, dasklkldsakadsp32525902j5,

    j6klj65kj45kkj45h, 3hjhjk3h34kjh34k34]

JSON 是相等的

prettyJson = groovy.json.JsonOutput.prettyPrint(groovy.json.JsonOutput.toJson(map))


{

    "gateway_splunky": {

        "appToken": "samplekey14124fggfs"

    },

    "MySpaceCredentials": {

        "credentials": [

            "samplekey352453sdffgsdfs",

            "dasklkldsakadsp32525902j5",

            "j6klj65kj45kkj45h",

            "3hjhjk3h34kjh34k34"

        ]

    },

【问题讨论】:

  • YAML 输出 YAML 并且 SnakeYAML 可以读取 JSON。 JsonOuput 只能输出 JSON。使用 SnakeYAML 回读 YAML 或使用例如回读 JSON 时是否出现任何错误? JsonSlurper?

标签: java jenkins serialization groovy yaml


【解决方案1】:

改用dumpAsMap()

import org.yaml.snakeyaml.*

Map map = [
    gateway_splunky: [appToken: 'samplekey14124fggfs'],
    MySpaceCredentials: [
        credentials: [
          'samplekey352453sdffgsdfs', 
          'dasklkldsakadsp32525902j5', 
          'j6klj65kj45kkj45h', 
          '3hjhjk3h34kjh34k34'
        ]
    ]
]

new Yaml().dumpAsMap(map)

生成:

gateway_splunky:
  appToken: samplekey14124fggfs
MySpaceCredentials:
  credentials:
  - samplekey352453sdffgsdfs
  - dasklkldsakadsp32525902j5
  - j6klj65kj45kkj45h
  - 3hjhjk3h34kjh34k34

【讨论】:

  • 太棒了。在这种情况下,您可以接受和/或投票赞成答案。
猜你喜欢
  • 1970-01-01
  • 2012-05-24
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-24
  • 2014-02-10
  • 1970-01-01
相关资源
最近更新 更多