Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

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

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:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...