Kas*_*iya 5 java serialization yaml pojo snakeyaml
我正在尝试序列化具有如下字段的 Java 实例。
\n\npublic 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}\nRun Code Online (Sandbox Code Playgroud)\n\n如何使用与实际字段名称不同的名称来序列化它们?这Gson可以通过使用@SerializedName("first-name")注释来实现,如下所示。
@SerializedName("first-name")\nprivate String firstName;\nRun Code Online (Sandbox Code Playgroud)\n\n里面有没有类似上面的东西snakeyaml。依赖项详细信息snakeyaml如下,
<dependency>\n <groupId>org.yaml</groupId>\n <artifactId>snakeyaml</artifactId>\n <version>1.17</version>\n </dependency>\nRun Code Online (Sandbox Code Playgroud)\n\n下面是程序的主类,其答案由flyx
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\nRun 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\nRun Code Online (Sandbox Code Playgroud)\n
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)
| 归档时间: |
|
| 查看次数: |
5917 次 |
| 最近记录: |