[英]Read Json as string from Yaml file
I want to parse a yaml file.我想解析一个 yaml 文件。 This file contains a field with json structure.
该文件包含一个具有 json 结构的字段。 I want this field as String in my java class.
我希望这个字段在我的 java 类中作为 String。
This is my java class:这是我的java类:
class A{
int field1;
boolean field2;
String field3;
}
This is the yaml file:这是 yaml 文件:
-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 来解析具有以下配置的 yaml:
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:每当我尝试读取我的 yaml 文件时,我都会收到错误消息:
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.我正在使用 Java 11。
Any idea what's wrong here?知道这里出了什么问题吗?
I just found a solution to my problem.我刚刚找到了解决我的问题的方法。 So if modify my yaml file like this:
因此,如果像这样修改我的 yaml 文件:
-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.所以我转义了 json 中的双引号,并在 json 的开头和结尾应用双引号,它被认为是 String。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.