如何迭代hocon配置对象?

时间:2016-01-25 07:31:58

标签: java playframework typesafe-config hocon

我有以下JSON,

 {
    "child1-name" : {
        "child1child1-name" : "child1child1-value",
        "child1child2-name" : "child1child2-value"
    },
    "child2" : {
        "child2child1-name" : "child2child1-value"
    },
    "child3-name" : "child3-value"
}

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

我希望实现以下Pusedo代码:

  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.

我正在考虑以下示例代码,

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的主要原因是我设置注释。现在在上面的代码中,我不确定如何设置注释。

1 个答案:

答案 0 :(得分:0)

在阅读并搜索对我来说很复杂的typesafe api后,我可以通过这样做来解决这个问题,

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)));

我希望将来帮助某人!