首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何迭代hocon配置对象?

如何迭代hocon配置对象?
EN

Stack Overflow用户
提问于 2016-01-25 15:31:58
回答 1查看 1.9K关注 0票数 0

我已经关注了JSON,

代码语言:javascript
复制
 {
    "child1-name" : {
        "child1child1-name" : "child1child1-value",
        "child1child2-name" : "child1child2-value"
    },
    "child2" : {
        "child2child1-name" : "child2child1-value"
    },
    "child3-name" : "child3-value"
}

现在,因为它是一个HOCON配置对象,所以我想遍历它并递归地检索每个元素。我希望遍历每个配置对象,并根据其类型(ArrayNode、ObjectNode、String等)设置适当的值(注释),并通过设置最终的配置对象返回该节点。

我想实现以下Pusedo代码:

代码语言:javascript
复制
  while(iterator.hasNext()) {
        Entry<String, ConfigValue> fld = iterator.next();
        // Now here access each object and value which will be of type of Configvalue
        //If(ConfigValueType.OBJECT)
             //set the required value 
       //else If(ConfigValueType.STRING)
              //set the required value 

    }
   //Once iteration done, set the new values in config and return final config object.

下面是我正在考虑的示例代码:

代码语言:javascript
复制
String jsonString = _mapper.writeValueAsString(jsonRoot); // jsonRoot is valid jsonNode object
       Config config = ConfigFactory.parseString(jsonString);

//Now,  I want to set comments by iterating the config object.
//I have gone through the following API’s,

ConfigObject co = config.root();
        Set<Entry<String, ConfigValue>> configNode2 =co.entrySet();
Iterator<Entry<String, ConfigValue>> itr =  configNode2.iterator();
        while(itr.hasNext()){
              Entry<String, ConfigValue> fld = itr.next();
               // **how to set comments and return the config object** .
       }

将JSON转换为HOCON的主要原因是为了让我设置注释。现在在上面的代码中,我不确定如何设置注释。

EN

回答 1

Stack Overflow用户

发布于 2016-02-01 19:06:22

在阅读和搜索了对我来说很复杂的类型安全api之后,我能够通过这样做来解决这个问题。

代码语言:javascript
复制
List<String> comments = Arrays.asList("A new","comment");
String jsonString = "{ \"a\" : 42 , \"b\" : 18 }";
Config config = ConfigFactory.parseString(jsonString);
ConfigObject co = config.root();
ConfigObject co2 = co;
Set<Entry<String, ConfigValue>> configNode2 = co.entrySet();
Iterator<Entry<String, ConfigValue>> itr = configNode2.iterator();
while(itr.hasNext()){
  Entry<String, ConfigValue> fld = itr.next();
  String key = fld.getKey();
  ConfigValue value = fld.getValue();
  ConfigOrigin oldOrigin = value.origin();
  ConfigOrigin newOrigin = oldOrigin.withComments(comments);
  ConfigValue newValue = value.withOrigin(newOrigin); 
  // fld.setValue(newValue); // This doesn't work: it's immutable
  co2 = co2.withValue(key,newValue);
}
config = co2.toConfig();
System.out.println(config.root().render(ConfigRenderOptions.concise().
  setComments(true).setFormatted(true)));

我希望这对将来的人有帮助!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34987267

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档