如何在Java中使用snake yaml序列化具有自定义名称的字段

Kas*_*iya 5 java serialization yaml pojo snakeyaml

我正在尝试序列化具有如下字段的 Java 实例。

\n\n
public class Person{\n    private String firstName;\n    private String lastName;\n\n    public String getFirstName() {\n\n        return firstName;\n    }\n\n    public void setFirstName(String firstName) {\n\n        this.firstName = firstName;\n    }\n\n    public String getLastName() {\n\n        return lastName;\n    }\n\n    public void setLastName(String lastName) {\n\n        this.lastName = lastName;\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

如何使用与实际字段名称不同的名称来序列化它们?这Gson可以通过使用@SerializedName("first-name")注释来实现,如下所示。

\n\n
@SerializedName("first-name")\nprivate String firstName;\n
Run Code Online (Sandbox Code Playgroud)\n\n

里面有没有类似上面的东西snakeyaml。依赖项详细信息snakeyaml如下,

\n\n
        <dependency>\n            <groupId>org.yaml</groupId>\n            <artifactId>snakeyaml</artifactId>\n            <version>1.17</version>\n        </dependency>\n
Run Code Online (Sandbox Code Playgroud)\n\n

下面是程序的主类,其答案由flyx

\n\n
public class Demo {\n\n    public static void main(String[] args) {\n\n        Person person = new Person();\n        person.setFirstName("Kasun");\n        person.setLastName("Siyambalapitiya");\n\n        Constructor constructor = new Constructor(Person.class);\n        Representer representer = new Representer();\n        TypeDescription personDesc = new TypeDescription(Person.class);\n        personDesc.substituteProperty("first-name", Person.class, "getFirstName", "setFirstName");\n        personDesc.substituteProperty("last-name", Person.class, "getLastName", "setLastName");\n        constructor.addTypeDescription(personDesc);\n        representer.addTypeDescription(personDesc);\n        Yaml yaml = new Yaml(constructor, representer);\n        String yamlString = yaml.dumpAs(person, Tag.MAP, DumperOptions.FlowStyle.BLOCK);\n\n        Path updateDescriptorFilePath =\n                Paths.get(File.separator + "tmp" + File.separator + "sample.json");\n        try {\n            FileUtils.writeStringToFile(updateDescriptorFilePath.toFile(), yamlString);\n        } catch (IOException e) {\n            System.out.println(e.getCause());\n        }\n    }\n}\n\n
Run Code Online (Sandbox Code Playgroud)\n\n

上述结果产生以下输出

\n\n
/tmp \xee\x82\xb0 cat sample.json\nfirst-name: Kasun\nlast-name: Siyambalapitiya\nfirstName: Kasun\nlastName: Siyambalapitiya\n /tmp \xee\x82\xb0  \n\n
Run Code Online (Sandbox Code Playgroud)\n

fly*_*lyx 4

Constructor constructor = new Constructor(Person.class);
Representer representer = new Representer();
TypeDescription personDesc = new TypeDescription(Person.class);
personDesc.substituteProperty("first-name", String.class,
        "getFirstName", "setFirstName");
constructor.addTypeDescription(personDesc);
representer.addTypeDescription(personDesc);
Yaml yaml = new Yaml(constructor, representer);
// and then load /dump your file with it
Run Code Online (Sandbox Code Playgroud)