Deserializing JSON with special characters into a string

Viewed 1954

I'm trying to parse a json file that looks like this

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

The code I have is currently this:

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);
}

I am getting an error:

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

Is there something special I need to do in order to read "<" as String?

I'm reading the file into a BufferReader with StandardCharsets.UTF_8 like this:

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

Edit: I actually do need defaultTyping for an ArrayList that has polymorphic types:

"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.
1 Answers

Remove OBJECT_MAPPER.enableDefaultTyping(); and it will work fine. This method is anyway deprecated.

In case you want to read automatic polymorphic types, use activateDefaultTyping(PolymorphicTypeValidator ptv).

Related