First we built two classes, the following two classes show a student has multiple mobile phone number contacts.
First Student class:
PackageCom.ming.yaml.beans;Importjava.util.ArrayList;Importjava.util.List;/*** Student class *@authorMing **/ Public classStudent {Private intID; PrivateString name; Private intAge ; //A student has multiple phone numbersList<tel> tels=NewArraylist<tel>(); Public intgetId () {returnID; } Public voidSetId (intID) { This. ID =ID; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } PublicList<tel>Gettels () {returntels; } Public voidSettels (list<tel>tels) { This. Tels =tels; } }
Then the contact person:
PackageCom.ming.yaml.beans;/*** Contact Phone class *@authorMing **/ Public classTel {PrivateString name; PrivateString Tel; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicString Gettel () {returnTel; } Public voidSettel (String tel) { This. Tel =Tel; } }
Test code:
PackageCom.ming.yaml;ImportJava.io.FileWriter;Importjava.util.ArrayList;Importjava.util.List;ImportOrg.yaml.snakeyaml.Yaml;Importcom.ming.yaml.beans.Student;ImportCom.ming.yaml.beans.Tel;/** * * @authorMing **/ Public classTest1 { Public Static voidMain (string[] args)throwsexception{Student Stu=NewStudent (); Stu.setname ("Lu Fei"); Stu.setage (24); Stu.setid (1); Tel T=NewTel (); T.setname ("Zhang San"); T.settel ("10123041445"); Tel T1=NewTel (); T1.setname ("John Doe"); T1.settel ("19923041455"); List<Tel> tels=NewArraylist<tel>(); Tels.add (t); Tels.add (t1); Stu.settels (tels); Yaml Yaml=NewYaml (); Yaml.dump (Stu,NewFileWriter ("Stu.yaml")); }}
The code for the final generated Stu.yaml file is as follows:
!! Com.ming.yaml.beans.studentage:24id:1name: Lu Fei tels:-{name: Zhang San, tel: ' 10123041445 '}-{name: John Doe, Tel: ' 19923041455 '}
Java implementations convert Java objects to YAML files