Introduction to the
YAML is a compact, non-markup Language (YAML Ain’t Markup Language). YAML is data-centric and uses whitespace, indentation, and lines to organize data, making presentation concise and readable. It is often used as a configuration file and is much cleaner than JSON.
YAML 1.2 (3rd Edition): yaml.org/spec/1.2/sp… Js – yaml: github.com/nodeca/js-y… YAML to JSON: nodeca.github. IO /js-yaml/
YAML design goals:
- Humans are easy to read
- It can be used for data exchange between different programs
- Suitable for describing data structures used by programs, especially scripting languages
- Rich expression ability and scalability
- Easy to use
YAML compares with XML and JSON
-
YAML and XML: Has the same advantages as XML, but is simpler, more agile, and so on
-
YAML and JSON
- JSON can be considered a subset of YAML, meaning that YAML can do everything JSON can do
- YAML can be expressed much more easily and easily than JSON, such as “strings don’t need quotes.” So YAML is easy to write in JSON format, but not recommended
- YAML can describe more complex structures than JSON, such as “relational anchors” that represent data references (such as references to duplicate data)
Scope of application of YAML
- YAML is particularly well suited for use in scripting languages because of its simplicity of implementation and low cost of parsing. List the existing language implementations: Ruby, Java, Perl, Python, PHP, OCaml, JavaScript. With the exception of Java, all are scripting languages.
- YAML is better for serialization. Because it is host language datatype straight forward, data flows between different languages are advised against YAML at this time due to compatibility issues.
- YAML is also good for configuration files. Ruby on Rails, for example, uses YAML for configuration. For ROR, this is natural and easy.
Grammar:
- Case sensitivity
- Use indentation to indicate hierarchy
- Do not indent TAB. Only the space key can be used. You are advised to use two Spaces
- The number of Spaces indented does not matter, as long as elements of the same rank are aligned to the left
-
Represents a comment that is ignored by the parser from this character all the way to the end of the line.
- Strings can be used without quotation marks, single or double quotation marks
The data structure
- Object: A collection of key-value pairs, also known as mapping/hashes/dictionary colon-delimited key-value pairs. Value), the Key must be written in the top column without a space before it, and the colon must be followed by a space after the Value. The same indentation belongs to the same map, for example, age: 12
- 1. An ordered set of values, also called a sequence/list.
- Scalar Scalar: The smallest scalar unit with minimum data, which cannot be divisible.
Objects and arrays can be nested arbitrarily into responsible data structures.
Data types: Supports string, integer, floating point, Boolean, date, NULL, object, and array
The sample
Multiple files can be contained in a file and separated by a hyphen. Optional symbol “…” Can be used to indicate the end of a file (useful in streaming communication, where you can send an end signal without closing the stream)
All key-value pairs with the same indent belong to the same map STR: this is a string # Strings do not use quotation marks by default: Str3: 'Content \n string' # Both single and double quotation marks can be used. Double quotation marks do not escape special characters str4: "Content \n string" # Double quotation marks do not escape special characters str5: # string can be multiple lines, starting with the second line, and must have a single space indent. Newline characters will be converted into space str6: this is a multi-line string str7: | # "|" said at the end of each line are all with a newline Foo Bar str8: > # ">" the last line with a newline Foo Bar str9: | Foo str10: | # + + retains the text block at the end of the line feed Foo str11: | - # - remove the newline at the end of the string Foo str12: | # of string can be inserted into HTML tags < p style = "color: red" > paragraph < / p > int: 10 Float: 9.99 bool: true # true, false # Date: 2015-08-23 # Date: 2015-08-23 # datetime: 2015-08-23T2:02:00.1z # ISO8601:2015-08-23T21:59:43.10-05:00 # ISO8601 date format Obj: field1: x field2: field21: xx field22: XXX # object: inline obj: field1: x field21: xx field22: XXX Field1: 'x', field21: 'xx', field22: 'XXX'} Array2: ['ele1', 'ele2', ['ele31', 'ele32']] # array3: -field1: x field2: xx field3: xxx - field1: x field2: xx field3: xxx set: ? ele ? Arr: - {field1: x, field2: x, field3: [1, 2, 3]} - {field1: x, field2: x, field3: [2, 3, 4]} arr2: - - a-b - - c-c # Type conversion: Use two exclamation marks followed by the basic data type to be converted, single quotes: used to convert custom objects # below the built-in type #!! Int # integer type #! Float # float type #!! Bool # Boolean type #! STR # String type #!! Binary # is a string #!! Timestamp # timestamp #!! Null # null #!! Set # set #! omap, !! Pairs # Key list or object list #!! Seq # sequence, also list #!! Test:!! STR 123 # Is marked with a question mark when the key is an array or object? [blue, reg, green]: xxx ? Ref: - &index1 a - b - *index1...Copy the code
Comparison of yamL to JSON results
{str2: 'Content: string ', str3:' content \n string ', str4: 'Content \n string ', str5: 'labor\' day', str6:' This is a multi-line string ', str7: 'Foo\nBar\n', str8: 'Foo Bar\n', str9: 'Foo\n', str10: 'Foo\n\n', str11: 'Foo', str12: '<p style="color: Red ">\n paragraph \n</p>\n', int: 10, float: 9.99, bool: true, Date: Sun Aug 23 2015 08:00:00 GMT+0800 (CST), date: '2015-08-23T02:02:00.1z', ISO8601: Mon Aug 24 2015 10:59:43 GMT+0800 (CST), SPACED: Mon Aug 24 2015 10:59:43 GMT+0800 (CST), obj: { field1: 'x', field2: { field21: 'xx', field22: 'xxx' } }, obj2: { field1: 'x', field2: { field21: 'xx', field22: 'xxx' } }, array: [ 'ele1', 'ele2', [ 'ele31', 'ele32' ] ], array2: [ 'ele1', 'ele2', [ 'ele31', 'ele32' ] ], array3: [ { field1: 'x', field2: 'xx', field3: 'xxx' }, { field1: 'x', field2: 'xx', field3: 'xxx' } ], set: { ele: null, ele2: null }, nested: { field1: 'x', arr: [ { field1: 'x', field2: 'x', field3: [ 1, 2, 3 ] }, { field1: 'x', field2: 'x', field3: [ 2, 3, 4 ] } ], arr2: [ [ 'a', 'b' ], [ 'c', 'c' ] ] }, test: '123', '? [blue, reg, green]': 'xxx', '? {a:xx, b:xx}': 'xx', ref: [ 'a', 'b', 'a' ] }Copy the code
Java parse
Introduction of depend on
<! -- https://mvnrepository.com/artifact/org.yaml/snakeyaml --> <dependency> <groupId>org.yaml</groupId> < artifactId > snakeyaml < / artifactId > < version > 1.20 < / version > < / dependency >Copy the code
Preparation entity:
public class Address {
private Long id;
private String address;
}
public class UserInfo {
private Long userId;
private String username;
}
public class User {
private Long id;
private String name;
private Integer age;
private Date birthday;
private float height;
private double score;
private boolean isVip;
private String[] hobbies;
private List<Address> addresses;
private UserInfo userInfo;
}
Copy the code
test
public static void main(String[] args) throws Exception { UserInfo userInfo = new UserInfo(1L, "xiaoming"); Address Address = new Address(1L, "Shanghai Pudong District "); Address address2 = new Address(2L, "Beijing "); List<Address> addresses = new ArrayList<Address>(); addresses.add(address); addresses.add(address2); User User = new User(1L, "小明", 20, new Date(), 178.88f, 99999.99, true, new String[]{"eat", "drink", "play", "happy"}, addresses, userInfo); Yaml yaml = new Yaml(); / / write file yaml. Dump (user, new FileWriter ("/Users/mengday/Desktop/user. Yml ")); / / read from the File User user1. = yaml loadAs (new FileInputStream (new File ("/Users/mengday/Desktop/User. Yml ")), the User. The class). System.out.println(user1.toString()); }Copy the code
Results:
!!!!! Com.example.demo.User addresses: - {address: Pudong New Area, Shanghai id: 1} - {address: Chaoyang District, Beijing ID: 2} age: 20 birthday: 2018-03-13T09:30:38.586z height: 178.88 Hobbies: [eat, drink, play, happy] iD: 1 name: xiaomingscore: 99999.99 userInfo: {userId: 1, username: xiaoming} vip: trueCopy the code
User{id=1, name=’ CST ‘, age=20, birthday=Tue Mar 13 17:30:38 CST 2018, height=178.88, score=99999.99, isVip=true, Hobbies =[eat, drink, play, happy], addresses=[Address{id=1, Address =’ Pudong ‘}, Address{id=2, Address =’ Beijing ‘}], userInfo=UserInfo{userId=1, username=’xiaoming’}}