将带有特殊字符的JSON反序列化为字符串

Deserializing JSON with special characters into a string

我正在尝试解析如下所示的 json 文件

{
  "foo": "v2",
  "bar": [
    "abc/bcf<object@twenty>.xyz",
    "abc/fgh<object@thirtu>.xyz"
  ]
}

我目前的代码是这样的:

Config.java

private static final ObjectMapper OBJECT_MAPPER;

    static {
        OBJECT_MAPPER = new ObjectMapper();
     OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        OBJECT_MAPPER.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
        OBJECT_MAPPER.enableDefaultTyping();
    }

@JsonCreator
    public Config(
            @JsonProperty(value = "foo", required = true) final String version,
            @JsonProperty(value = "bar") final List<String> barTypes) {
     // rest of constructor
}

public static Config fromJson(final Reader reader)
            throws IOException {
        return OBJECT_MAPPER.readValue(reader, Config.class);
}

我收到一个错误:

Failed to parse type 'abc/bcf<object@twenty>.xyz' (remaining: '<object@twenty>.xyz'): Cannot locate class 'abc/bcf', problem: abc/bcf"

为了将“<”读作字符串,我需要做一些特别的事情吗?

我正在使用 StandardCharsets 将文件读入 BufferReader。UTF_8 像这样:

try (BufferedReader reader = Files.newBufferedReader(configFile.toPath(), StandardCharsets.UTF_8)) {
            config = Config.fromJson(reader);
}

编辑:我确实需要为具有多态类型的 ArrayList 使用 defaultTyping:

"Vehicles": [
    "java.util.ArrayList",
    [
      {
        "name": "Car"
      },
      {
        "name": "Train"
      }
   ]

I currently use a MixIn for declaring the subtypes. However, this stops working if I remove DefaultTyping.

删除OBJECT_MAPPER.enableDefaultTyping();,它将正常工作。这种方法无论如何都被弃用了。

如果您想阅读自动多态类型,请使用activateDefaultTyping(PolymorphicTypeValidator ptv)