0

I want to parse a yaml file. This file contains a field with json structure. I want this field as String in my java class.

This is my java class:

class A{
  int field1;
  boolean field2;
  String field3;
}

This is the yaml file:

-field1: 2022-12-23T21:45:26.097+01
 field2: true
 field3: {"x":"apple", "y": { "z":10, "w":[{ "a": 11}]}}

I'm using Objectmapper for parsing yaml with the following configuration:

ObjectMapper mapper = new Jackson2ObjectMapperBuilder()
                .serializationInclusion(JsonInclude.Include.NON_NULL)
                .modulesToInstall(new JavaTimeModule())
                .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                .featuresToDisable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
                .factory(new YAMLFactory())
                .build();

And whenever I try to read my yaml file I get an error:

    com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.lang.String` from Object value (token `JsonToken.START_OBJECT`)
 at [Source: (File); line: 3, column: 11] (through reference chain: java.lang.Object[][0]->company_related_class)

I'm using java 11.

Any idea what's wrong here?

HowToTellAChild
  • 623
  • 1
  • 9
  • 21

1 Answers1

0

I just found a solution to my problem. So if modify my yaml file like this:

-field1: 2022-12-23T21:45:26.097+01
 field2: true
 field3: "{\"x\":\"apple\", \"y\": { \"z\":10, \"w\":[{ \"a\": 11}]}}"

So I escape the double quotes in the json and apply double quotes at the start and end of the json it is considered as String.

HowToTellAChild
  • 623
  • 1
  • 9
  • 21
  • 1
    You can make this a little more readable by enclosing the entire JSON in single-quotes (that way you do not have the escape the individual double quotes). This approach and other (potentially better) approaches are mentioned in this answer here - https://stackoverflow.com/questions/9532840/embedding-json-data-into-yaml-file – Vini Dec 24 '22 at 02:35