简体   繁体   中英

Jackson YAML reader not parsing yaml file properly

I'm trying to parse a YAML file with Jackson. Please find the relevant files below.

Yaml file:

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

Model:

@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;
    }
}

I am trying to read the yaml contents as follows:

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

But when I try to print the parsed data, this is what I get:

[{
    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
}]

How can I make it read such that I get the following output, instead of the array I am receiving?

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

So I was able to figure out the right way to store the values. I had to change the POJO to the following:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ParamsMain {

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

}

This helped me store the data in the following format:

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

I used the following code to print what is being parsed:

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));

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