How to create a DSL Groovy config file using an arbitrary Map (dynamic object)

怎甘沉沦 提交于 2019-12-14 03:27:34

问题


How do I convert an arbitrary Groovy map / list to the config style DSL syntax that Groovy provides?

Example:

def config = [
    'test': 'lalala',
    'nestedObject': [
        foo1: 'foo1 val',
        foo2: 'foo2 val',
        nested2: [
            anInt: 5,
            anArray: ['a', 'b', 'c'],
            anIntArray: [1, 2, 3]
        ]
    ]
]

To something like:

test = 'lalala'
nestedObject {
    foo1 = 'foo1 val'
    foo2 = 'foo2 val'
    nested2 {
        anInt = 5
        anArray = ['a', 'b', 'c']
        anIntArray = [1, 2, 3]
    }
}

UPDATE:

  • Re-appropriating this post to explicitly ask for a dynamic/generalized solution.
  • This makes it a unique question and unlike the following which assumes a known map at its initialization state: How to create ConfigObject using only nested maps in Grails?

回答1:


If you know the nested Map structure in advance, your solution will work. If you need to do this on an unknown arbitrary nested Map structure, try something like this:

import groovy.util.ConfigObject

def mapToConfig
mapToConfig = { Map map ->
    map.collectEntries { k, v ->
        v instanceof Map ? [(k):mapToConfig(v)] : [(k):v]
    } as ConfigObject
}

Given your input and the above closure definition, the following print statement:

println mapToConfig(config).prettyPrint()

Yields this output:

test='lalala'
nestedObject {
    foo1='foo1 val'
    foo2='foo2 val'
    nested2 {
        anInt=5
        anArray=['a', 'b', 'c']
        anIntArray=[1, 2, 3]
    }
}



回答2:


Just convert each Map into a ConfigObject and then pretty-print it:

import groovy.util.ConfigObject

def config = [
    'test': 'lalala',
    'nestedObject': [
        foo1: 'foo1 val',
        foo2: 'foo2 val',
        nested2: [
            anInt: 5,
            anArray: ['a', 'b', 'c'],
            anIntArray: [1, 2, 3]
        ] as ConfigObject
    ] as ConfigObject
] as ConfigObject

println config.prettyPrint()

All credit goes to: How to create ConfigObject using only nested maps in Grails?

(I just wanted people to know you can do this outside of Grails and initially I didn't realize how the pretty printing was invoked. I was confused with JsonOutput.prettyPrint())

Thanks @Steinar



来源:https://stackoverflow.com/questions/39497150/how-to-create-a-dsl-groovy-config-file-using-an-arbitrary-map-dynamic-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!