我已经关注了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的主要原因是为了让我设置注释。现在在上面的代码中,我不确定如何设置注释。
发布于 2016-02-01 19:06:22
在阅读和搜索了对我来说很复杂的类型安全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)));我希望这对将来的人有帮助!
https://stackoverflow.com/questions/34987267
复制相似问题