简体   繁体   中英

Read Json as string from Yaml file

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?

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.

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