简体   繁体   中英

Why I have this error on parsing Block of YAML?

I have this block of YAML:

- operationId: "getG"
  applicationName: "c"

- operationId: "get"
  applicationName: "c"

And actually I want to parse it with Jackson Library of YAML and I have this code:

public class YamlProcessor {

    ListYamlEntries> entries;
}

@Getter //lombok
@Setter //lombok
public class YamlEntries {

    @JsonProperty("applicationName")
    String applicationName;

    @JsonProperty("operationId")
    String operationId;

}
public YamlProcessor yamlParser(String file) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
        objectMapper.findAndRegisterModules();
        YamlProcessor yamlEntries = objectMapper.readValue(new File(file), YamlProcessor.class);

        yamlEntries.getEntries().forEach(valuesOfYaml -> {
                log.info("applicationName: " + valuesOfYaml.getApplicationName());
                log.info("operationId: " + valuesOfYaml.getOperationId());

        });

        return yamlEntries;
    }

But I get this error and I can't figure it out why:

Cannot deserialize instance of `[....objects.YamlEntries;` out of START_OBJECT token
 at [Source: (File); line: 10, column: 1]

Can anyone figure it out and help me?

I don't know exactly what you want to parse, but the yaml you have posted should be parsed in a List<YamlEntries> instead of List<Map<String, YamlEntries>>

If you want to create a list of maps your yaml should be something like:

 - key1:
     operationId: "getG"
     applicationName: "c"
   key2:
     operationId: "getG"
     applicationName: "c"
    

 - otherkey1:
     operationId: "get"
     applicationName: "c"
   otherkey2:
     operationId: "getG"
     applicationName: "c"

If you want to parse a List<YamlEntries> this should work for you.

in the yaml you have to have something like

entries:
  - operationId: "getG"
    applicationName: "c"

  - operationId: "get"
    applicationName: "c"

And then a class like this to map the properties into a List of YamlEntries:

@Component
@ConfigurationProperties(prefix = "entries")
public class Endpoints {
  private List<YamlEntries> yamlEntries;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM