我正在使用 SnakeYaml 在 Java 中加载/转储数据。为此,我创建了一个带有字段的自定义类,假设该类如下所示:
public class Person {
private String name;
private String lastName;
private String address;
public Person() {
// Do nothing
}
// Getters and setters initialized for all the fields
}
现在,我想要的是,当我使用 SnakeYaml 将 Person 对象写入文件时,我希望字段按照它们在类中定义的顺序排列。
例如
name: Patrick
lastName: Star
Age : 42
问题在于,对于更高级的示例,无法实现这种排序。目前我正在写入/转储到一个 yaml 文件,如下所示:
Constructor struct = new Constructor(YamlIteratorModel.class);
Yaml yaml = new Yaml(struct);
try {
String path = "Some/File/Path/yamlfile.yaml";
FileWriter writer = new FileWriter(path);
yaml.dump(iteratorModel, writer);
} catch (IOExcepton e) {
// Do something
}
我还尝试过创建一个Representer类,它扩展 Representer 并以类似的方式调用 Yaml 构造函数。这个取自另一篇文章,它对我不起作用,因为它只按我不完全确定的顺序对属性进行排序(现在找不到链接,但如果我再次找到它会更新)..
public class ConfigurationModelRepresenter extends Representer {
/**
* Create object without specified dumper object
*/
public ConfigurationModelRepresenter() {
super();
}
/**
* Create object with dumper options
*
* @param options
*/
public ConfigurationModelRepresenter(DumperOptions options) {
super(options);
}
/** {@inheritDoc} */
@Override
protected Set<Property> getProperties(Class< ? extends Object> type) {
Set<Property> propertySet;
if (typeDefinitions.containsKey(type)) {
propertySet = typeDefinitions.get(type).getProperties();
} else {
propertySet = getPropertyUtils().getProperties(type);
}
List<Property> propsList = new ArrayList<>(propertySet);
Collections.sort(propsList, new BeanPropertyComparator());
return new LinkedHashSet<>(propsList);
}
class BeanPropertyComparator implements Comparator<Property> {
@Override
public int compare(Property p1, Property p2) {
// p1.getType().get
if (p1.getType().getCanonicalName().contains("util") && !p2.getType().getCanonicalName().contains("util")) {
return 1;
} else if (p2.getName().endsWith("Name") || p2.getName().equalsIgnoreCase("name")) {
return 1;
} else {
return -1;
}
}
}
}
总结:在将对象转储到 YAML 文件(使用 SnakeYaml)时如何维护排序,例如自定义类中定义的字段出现的顺序?
请参阅此问题,其中讨论了您无法通过反射获取已声明字段的行号。
加上反射为您提供没有特定顺序的类字段这一事实,很明显,在运行时无法观察类中声明字段的顺序,因此您无法对 YAML 中的键进行排序根据它们在源中的位置/顺序输出,因为您无法知道该顺序。
补救措施是将订单的知识传输到运行时。一些可能的方法可能是:
weight
定义生成的 YAML 键的位置的注释每个字段(丑陋,因为您需要在字段上进行注释)。我建议不要使用任何这些解决方案。YAML 规范明确指出,关键顺序不得传达内容信息,如果顺序对您很重要,那么您已经违反了 YAML 规范,应该切换到更能满足您需求的格式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句