GVKun编程网logo

Yaml(yaml文件)

9

在这里,我们将给大家分享关于Yaml的知识,让您更了解yaml文件的本质,同时也会涉及到如何更有效地c–如何通过yaml-cpp加载YAML文件?、GCP:根据dispatch.yaml规则配置app

在这里,我们将给大家分享关于Yaml的知识,让您更了解yaml文件的本质,同时也会涉及到如何更有效地c – 如何通过yaml-cpp加载YAML文件?、GCP:根据 dispatch.yaml 规则配置 app.yaml、Jackson YAML 阅读器未正确解析 yaml 文件、JAVA使用SnakeYAML解析与序列化YAML的内容。

本文目录一览:

Yaml(yaml文件)

Yaml(yaml文件)

Yaml 介绍

模块化的css框架,真正灵活,方便的响应式网站。 YAML提供了一套完整匹配的积木来创建复杂的网站。网格,导航,表格,排版模块和所有提供的附加组件无缝地在一起协同工作。  

网站地址:http://www.yaml.de/

GitHub:https://github.com/yamlcss/yaml

网站描述:模块化的CSS框架,

Yaml官方网站

官方网站:http://www.yaml.de/

如果觉得小编网站内容还不错,欢迎将小编网站 推荐给程序员好友。

c – 如何通过yaml-cpp加载YAML文件?

c – 如何通过yaml-cpp加载YAML文件?

我是 yaml-cpp的新手,我尝试了最简单的程序,但失败了,也没有找到作者的谷歌/ github网站的答案.
#include <iostream>
#include "yaml-cpp/yaml.h"

using namespace std;

int main()
{
    YAML::Node config = YAML::LoadFile("sample.yaml");
    return 0;
}

来自YAML官方网站的sample.yaml样本

--- !clarkevans.com/^invoice
invoice: 34843
date   : 2001-01-23
bill-to: &id001
    given  : Chris
    family : Dumars
    address:
        lines: |
            458 Walkman Dr.
            Suite #292
        city    : Royal Oak
        state   : MI
        postal  : 48046
ship-to: *id001
product:
    - sku         : BL394D
      quantity    : 4
      description : Basketball
      price       : 450.00
    - sku         : BL4438H
      quantity    : 1
      description : Super Hoop
      price       : 2392.00
tax  : 251.42
total: 4443.52
comments: >
    Late afternoon is best.
    Backup contact is Nancy
    Billsmer @ 338-4338.

错误消息如下:

libc++abi.dylib: terminating with uncaught exception of type YAML::BadFile: yaml-cpp: error at line 0,column 0: bad file

我可以知道这是什么问题吗?它是库构建问题还是YAML语法问题或API使用问题?

发展环境

MacOSX10.9 c 11 IDE:QtCreator3.0.1 yaml-cpp 0.5.1

[解决了]
我犯了愚蠢的错误,我加载了错误的sample.yaml路径.

解决方法

看来yaml-cpp无法找到您的文件.你能加载任何文件吗?确保该文件位于程序的工作目录中,为了保持合理性,请确保首先加载一个非常简单的文件.

GCP:根据 dispatch.yaml 规则配置 app.yaml

GCP:根据 dispatch.yaml 规则配置 app.yaml

如何解决GCP:根据 dispatch.yaml 规则配置 app.yaml?

我配置了两个服务,其中一个是默认服务。但是通过 DNS 查询 https://gcpdev.company.com/one 服务时,却无法访问到项目文件。例如:

如果我直接输入这个网址,会返回 500 错误:

https://gcpdev.company.com/vendor-es2017.65ff9b5300ddf6707a5c.js

正确打开文件的是:

https://gcpdev.company.com/one/vendor-es2017.65ff9b5300ddf6707a5c.js

我的配置有问题吗?这些是 default 项目的文件:

dispatch.yaml

dispatch:
  - url: "gcpdev.company.com/one/*"
    service: default
  - url: "gcpdev.company.com/two/*"
    service: two-ui

app.yaml

runtime: nodejs12    
service: default

handlers:
  - url: /one/(.*\.(gif|png|jpg|less|json|woff|woff2|ttf|eot|scss|css|js|ico|svg)(|\.map))$
    static_files: dist/\1
    upload: dist/(.*)(|\.map)

  - url: /one/assets/data/appConfig.json
    static_files: dist/assets/data/appConfig.json
    upload: dist/assets/data/appConfig.json

  - url: /one/(.*)
    static_files: dist/index.html
    upload: dist/index.html

对于 two-ui 项目,我有相同的 dispatch.yaml 和类似的 app.yaml

 runtime: nodejs12        
 service: two-ui
    
 handlers:
   - url: /two/(.*\.(gif|png|jpg|less|json|woff|woff2|ttf|eot|scss|css|js|ico|svg)(|\.map))$
     static_files: dist/\1
     upload: dist/(.*)(|\.map)
    
   - url: /two/assets/data/appConfig.json
     static_files: dist/assets/data/appConfig.json
     upload: dist/assets/data/appConfig.json
    
   - url: /two/(.*)
     static_files: dist/index.html
     upload: dist/index.html

解决方法

您的调度规则提到您必须使用:

  • gcpdev.company.com/one/*
  • gcpdev.company.com/two/*

然后,预计对 gcpdev.company.com/* 的调用会失败。没有任何规则规定如何使用该模式。

关于:

正确打开文件的是: https://gcpdev.company.com/one/vendor-es2017.65ff9b5300ddf6707a5c.js

非常值得一看Examples:

例如:

dispatch:
  # Default service serves the typical web resources and all static resources.
  - url: "*/favicon.ico"
    service: default**strong text**

如果您想提供没有 /one/*/two/* 模式的静态文件,您可能需要添加与上述类似的内容。

关于如何在您的服务上提供静态文件,检查 Handlers element 是下一步。我的建议是首先关注 dispatcher,然后关注 app.yaml 中的处理程序。

Jackson YAML 阅读器未正确解析 yaml 文件

Jackson YAML 阅读器未正确解析 yaml 文件

如何解决Jackson YAML 阅读器未正确解析 yaml 文件?

我正在尝试使用 Jackson 解析 YAML 文件。请在下面找到相关文件。

Yaml 文件:

params:
 - param-one : abcd
 - param-two : abcd
 - param-three : abcd
 - param-four : abcd

型号:

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
        "params"
})
@Data
public class ParamsMain {

    @JsonProperty("params")
    private List<Params> params = null;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonPropertyOrder({
            "param-one","param-two","param-three","param-four"
    })
    @Data
    public static class Params {

        @JsonProperty("param-one")
        private String paramOne;

        @JsonProperty("param-two")
        private String paramTwo;

        @JsonProperty("param-three")
        private String paramThree;

        @JsonProperty("param-four")
        private String paramFour;
    }
}

我正在尝试按如下方式读取 yaml 内容:

ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
ParamsMain paramsMain = objectMapper.readValue(<PATH_OF_YAML_FILE>,ParamsMain.class);

但是当我尝试打印解析的数据时,这就是我得到的:

[{
    param-one: abcd
    param-two: null
    param-three: null
    param-four: null
},{
    param-one: null
    param-two: abcd
    param-three: null
    param-four: null
},{
    param-one: null
    param-two: null
    param-three: abcd
    param-four: null
},{
    param-one: null
    param-two: null
    param-three: null
    param-four: abcd
}]

我怎样才能读取它以获得以下输出,而不是我收到的数组?

param-one: abcd
param-two: abcd
param-three: abcd
param-four: abcd

解决方法

所以我能够找出存储值的正确方法。我不得不将 POJO 更改为以下内容:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ParamsMain {

    @JsonProperty("params")
    private Map<String,String>[] params;

}

这帮助我以以下格式存储数据:

{{param-one=abcd},{param-two=abcd},{param-three=abcd},{param-four=abcd}}

我使用以下代码打印正在解析的内容:

ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
ParamsMain paramsMain = objectMapper.readValue(<PATH_OF_YAML_FILE>,ParamsMain.class);


//code to print
System.out.println(ReflectionToStringBuilder.toString(paramsMain,ToStringStyle.MULTI_LINE_STYLE));

JAVA使用SnakeYAML解析与序列化YAML

JAVA使用SnakeYAML解析与序列化YAML

1.概述

本文,我们将学习如何使用SnakeYAML库将
YAML文档转换为Java对象,以及JAVA对象如何序列化为YAML文档

2.项目设置

要在项目中使用SnakeYAML,需要添加Maven依赖项(可在此处找到最新版本):

<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.25</version>
</dependency>

3.入口点

YAML类是API的入口点:

Yaml yaml = new Yaml()

由于实现不是线程安全的,因此不同的线程必须具有自己的Yaml实例。

4.加载YAML文档

SnakeYAML支持从StringInputStream加载文档,我们从定义一个简单的YAML文档开始,然后将文件命名为customer.yaml

firstName: "John"
lastName: "Doe"
age: 20

4.1。基本用法

现在,我们将使用Yaml类来解析上述YAML文档:

Yaml yaml = new Yaml();
InputStream inputStream = this.getClass()
  .getClassLoader()
  .getResourceAsstream("customer.yaml");
Map<String,Object> obj = yaml.load(inputStream);
System.out.println(obj);

上面的代码生成以下输出:

{firstName=John,lastName=Doe,age=20}

默认情况下,load()方法返回一个Map对象。查询Map对象时,我们需要事先知道属性键的名称,否则容易出错。更好的办法是自定义类型。

4.2自定义类型解析

SnakeYAML提供了一种将文档解析为自定义类型的方法

让我们定义一个Customer类,然后尝试再次加载该文档:

public class Customer {
 
    private String firstName;
    private String lastName;
    private int age;
 
    // getters and setters
}

现在我么来加载:

Yaml yaml = new Yaml();
InputStream inputStream = this.getClass()
 .getClassLoader()
 .getResourceAsstream("customer.yaml");
Customer customer = yaml.load(inputStream);

还有一种方法是使用Constructor:

Yaml yaml = new Yaml(new Constructor(Customer.class));

4.3。隐式类型

如果没有为给定属性定义类型,则库会自动将值转换为隐式type

例如:

1.0 -> Float
42 -> Integer
2009-03-30 -> Date

让我们使用一个TestCase来测试这种隐式类型转换:

@Test
public void whenLoadYAML_thenLoadCorrectImplicitTypes() {
   Yaml yaml = new Yaml();
   Map<Object,Object> document = yaml.load("3.0: 2018-07-22");
  
   assertNotNull(document);
   assertEquals(1,document.size());
   assertTrue(document.containsKey(3.0d));   
}

4.4 嵌套对象

SnakeYAML 支持嵌套的复杂类型。

让我们向“ customer.yaml”添加“ 联系方式”  和“ 地址” 详细信息并将新文件另存为customer_with_contact_details_and_address.yaml.

现在,我们将分析新的YAML文档:

firstName: "John"
lastName: "Doe"
age: 31
contactDetails:
   - type: "mobile"
     number: 123456789
   - type: "landline"
     number: 456786868
homeAddress:
   line: "Xyz,DEF Street"
   city: "City Y"
   state: "State Y"
   zip: 345657

我们来更新java类:

public class Customer {
    private String firstName;
    private String lastName;
    private int age;
    private List<Contact> 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
}

现在,我们来测试下Yamlload()

@Test
public 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。类型安全的集合

当给定java类的一个或多个属性是泛型集合类时,需要通过TypeDescription来指定泛型类型,以以便可以正确解析。

让我们假设一个 一个Customer拥有多个Contact

firstName: "John"
lastName: "Doe"
age: 31
contactDetails:
   - { type: "mobile",number: 123456789}
   - { type: "landline",number: 123456789}

为了能正确解析,我们可以在顶级类上为给定属性指定TypeDescription 

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。载入多个文件

在某些情况下,单个文件中可能有多个YAML文档,而我们想解析所有文档。所述YAML类提供了一个LOADALL()方法来完成这种类型的解析。

假设下面的内容在一个文件中:

---
firstName: "John"
lastName: "Doe"
age: 20
---
firstName: "Jack"
lastName: "Jones"
age: 25

我们可以使用loadAll()方法解析以上内容,如以下代码示例所示:

@Test
public 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(2,count);
}

5.生成YAML文件

SnakeYAML 支持 将java对象序列化为yml。

5.1。基本用法

我们将从一个将Map <String,Object>的实例转储到YAML文档(String)的简单示例开始:

@Test
public void whenDumpMap_thenGenerateCorrectYAML() {
    Map<String,Object> data = new LinkedHashMap<String,Object>();
    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());
}

上面的代码产生以下输出(请注意,使用LinkedHashMap的实例将保留输出数据的顺序):

name: Silenthand Olleander
race: Human
traits: [ONE_HAND,ONE_EYE]

5.2。自定义Java对象

我们还可以选择将自定义java类型转储到输出流中

@Test
public 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());
}

生成内容会包含!!com.baeldung.snakeyaml.Customer,为了避免在输出文件中使用标签名,我们可以使用库提供的  dumpAs()方法。

因此,在上面的代码中,我们可以进行以下调整以删除标记:

yaml.dumpAs(customer,Tag.MAP,null);

六 结语

本文说明了SnakeYAML库解析和序列化YAML文档。

所有示例都可以在GitHub项目中找到。

附录

  • 英文原文: Parsing YAML with SnakeYAML

作者:Jadepeng
出处:jqpeng的技术记事本--http://www.cnblogs.com/xiaoqi
您的支持是对博主最大的鼓励,感谢您的认真阅读。
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

关于Yamlyaml文件的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于c – 如何通过yaml-cpp加载YAML文件?、GCP:根据 dispatch.yaml 规则配置 app.yaml、Jackson YAML 阅读器未正确解析 yaml 文件、JAVA使用SnakeYAML解析与序列化YAML的相关知识,请在本站寻找。

本文标签: