Home > Enterprise >  Read Json as string from Yaml file
Read Json as string from Yaml file

Time:12-27

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?

CodePudding user response:

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.

  • Related