In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "JAVA how to serialize YAML based on SnakeYAML". In daily operation, I believe many people have doubts about how to serialize YAML based on JAVA. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubt of "how to serialize YAML based on JAVA based on SnakeYAML". Next, please follow the editor to study!
1. Overview
In this article, we will learn how to use the SnakeYAML library to set the
YAML documents are converted to Java objects, and how JAVA objects are serialized into YAML documents.
two。 Project setup
To use SnakeYAML in your project, you need to add a Maven dependency (you can find the latest version here):
Org.yaml snakeyaml 1.25
3. Entry point
This YAML class is the entry point for API:
Yaml yaml = new Yaml ()
Because the implementation is not thread-safe, different threads must have their own Yaml instances.
4. Load YAML document
SnakeYAML supports loading documents from String or InputStream. Let's start by defining a simple YAML document and then name the file customer.yaml:
FirstName: "John" lastName: "Doe" age: 20
4.1 basic usage
Now we will use the Yaml class to parse the above YAML document:
Yaml yaml = new Yaml (); InputStream inputStream = this.getClass () .getClassLoader () .getResourceAsStream ("customer.yaml"); Map obj = yaml.load (inputStream); System.out.println (obj)
The above code produces the following output:
{firstName=John, lastName=Doe, age=20}
By default, the load () method returns a Map object. When querying the Map object, we need to know the name of the property key in advance, otherwise it is prone to error. A better approach is to customize the type.
4.2 Custom type resolution
SnakeYAML provides a way to parse documents into custom types
Let's define a Customer class and try to load the document again:
Public class Customer {private String firstName; private String lastName; private int age; / / getters and setters}
Now let's load:
Yaml yaml = new Yaml (); InputStream inputStream = this.getClass () .getClassLoader () .getResourceAsStream ("customer.yaml"); Customer customer = yaml.load (inputStream)
Another way is to use Constructor:
Yaml yaml = new Yaml (new Constructor (Customer.class))
4.3 implicit type
If no type is defined for a given property, the library automatically converts the value to an implicit type.
For example:
1.0-> Float42-> Integer2009-03-30-> Date
Let's use a TestCase to test this implicit type conversion:
@ Testpublic void whenLoadYAML_thenLoadCorrectImplicitTypes () {Yaml yaml = new Yaml (); Map document = yaml.load ("2018-07-22"); assertNotNull (document); assertEquals (1, document.size ()); assertTrue (document.containsKey (3.0d));}
4.4 nested objects
SnakeYAML supports nested complex types.
Let's add contact details and address details to customer.yaml and save the new file as customer_with_contact_details_and_address.yaml.
Now, we will analyze the new YAML document:
FirstName: "John" lastName: "Doe" age: 31contactDetails:-type: "mobile" number: 123456789-type: "landline" number: 456786868homeAddress: line: "Xyz, DEF Street" city: "City Y" state: "State Y" zip: 345657
Let's update the java class:
Public class Customer {private String firstName; private String lastName; private int age; private List contactDetails; private Address homeAddress; / / getters and setters} public class Contact {private String type; private int number; / / getters and setters} public class Address {private String line; private String city; private String state; private Integer zip; / / getters and setters}
Now, let's test Yaml#load ():
@ Testpublic void whenLoadYAMLDocumentWithTopLevelClass_thenLoadCorrectJavaObjectWithNestedObjects () {Yaml yaml = new Yaml (new Constructor (Customer.class)); InputStream inputStream = this.getClass () .getClassLoader () .getResourceAsStream ("yaml/customer_with_contact_details_and_address.yaml"); Customer customer = yaml.load (inputStream); assertNotNull (customer); assertEquals ("John", customer.getFirstName ()); assertEquals ("Doe", customer.getLastName ()); assertEquals (31, customer.getAge ()); assertNotNull (customer.getContactDetails ()) AssertEquals (2, customer.getContactDetails (). Size (); assertEquals ("mobile", customer.getContactDetails (). Get (0). GetType ()); assertEquals (123456789, customer.getContactDetails (). Get (0). GetNumber ()); assertEquals ("landline", customer.getContactDetails (). Get (1). GetType ()); assertEquals (456786868, customer.getContactDetails () .get (1). GetNumber ()); assertNotNull (customer.getHomeAddress ()) AssertEquals ("Xyz, DEF Street", customer.getHomeAddress () .getLine ());}
4.5 Type-safe collections
When one or more properties of a given Java class are generic collection classes, you need to specify the generic type through TypeDescription so that it can be parsed correctly.
Let's assume that a Customer has multiple Contact:
FirstName: "John" lastName: "Doe" age: 31contactDetails:-{type: "mobile", number: 123456789}-{type: "landline", number: 123456789}
For proper parsing, we can specify TypeDescription for a given property on the top-level class:
Constructor constructor = new Constructor (Customer.class); TypeDescription customTypeDescription = new TypeDescription (Customer.class); customTypeDescription.addPropertyParameters ("contactDetails", Contact.class); constructor.addTypeDescription (customTypeDescription); Yaml yaml = new Yaml (constructor)
4.6 load multiple files
In some cases, there may be multiple YAML documents in a single file, and we want to parse all of them. The YAML class provides a LOADALL () method to complete this type of parsing.
Suppose the following is in a file:
-firstName: "John" lastName: "Doe" age: 20---firstName: "Jack" lastName: "Jones" age: 25
We can parse the above using the loadAll () method, as shown in the following code example:
@ Testpublic void whenLoadMultipleYAMLDocuments_thenLoadCorrectJavaObjects () {Yaml yaml = new Yaml (new Constructor (Customer.class)); InputStream inputStream = this.getClass () .getClassLoader () .getResourceAsStream ("yaml/customers.yaml"); int count = 0; for (Object object: yaml.loadAll (inputStream)) {count++; assertTrue (object instanceof Customer);} assertEquals (2Journal count);}
5. Generate YAML file
SnakeYAML supports serialization of java objects to yml.
5.1 basic usage
We will start with a simple example of dumping an instance of Map into an YAML document (String):
@ Testpublic void whenDumpMap_thenGenerateCorrectYAML () {Map data = new LinkedHashMap (); data.put ("name", "Silenthand Olleander"); data.put ("race", "Human"); data.put ("traits", new String [] {"ONE_HAND", "ONE_EYE"}); Yaml yaml = new Yaml (); StringWriter writer = new StringWriter (); yaml.dump (data, writer); String expectedYaml = "name: Silenthand Olleander\ nrace: Human\ ntraits: [ONE_HAND, ONE_EYE]\ n" AssertEquals (expectedYaml, writer.toString ();}
The above code produces the following output (note that the instance using LinkedHashMap retains the order of the output data):
Name: Silenthand Olleanderrace: Humantraits: [ONE_HAND, ONE_EYE]
5.2 Custom Java object
We can also choose to dump the custom Java type into the output stream.
@ Testpublic void whenDumpACustomType_thenGenerateCorrectYAML () {Customer customer = new Customer (); customer.setAge (45); customer.setFirstName ("Greg"); customer.setLastName ("McDowell"); Yaml yaml = new Yaml (); StringWriter writer = new StringWriter (); yaml.dump (customer, writer); String expectedYaml = "! com.baeldung.snakeyaml.Customer {age: 45, contactDetails: null, firstName: Greg,\ n homeAddress: null, lastName: McDowell}\ n"; assertEquals (expectedYaml, writer.toString ());}
The generated content will contain! com.baeldung.snakeyaml.Customer, and to avoid using tag signatures in the output file, we can use the dumpAs () method provided by the library.
Therefore, in the above code, we can make the following adjustments to delete the tag:
Yaml.dumpAs (customer, Tag.MAP, null)
At this point, the study on "how JAVA serializes YAML based on SnakeYAML" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.