3

I have a pojo:

public class A {

  public int a;
  public String anyJson1;
  public String anyJson2;
  public String anyJson3;
}

i want anyJsonX field to accept any json. for example:

{"a":5, "anyJson1":[1,2,3], "anyJson2:4, "anyJson3":{"c":"d"}}

i tried to put @JsonRawValue on those fields, but no success

nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token

piotrek
  • 13,982
  • 13
  • 79
  • 165

1 Answers1

7

@JsonRawValue only works for serialization.

If you can change the String fields to Object you will be fine.

In case you cannot you can use a simple custom deserializer:

public class AnythingToString extends JsonDeserializer<String> {

    @Override
    public String deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        TreeNode tree = jp.getCodec().readTree(jp);
        return tree.toString();
    }
}

And then use it in your model:

public static class A {

    public A() {}

    private int a;
    @JsonDeserialize(using = AnythingToString.class)
    private String anyJson1;
    @JsonDeserialize(using = AnythingToString.class)
    private String anyJson2;
    @JsonDeserialize(using = AnythingToString.class)
    private String anyJson3;
Franjavi
  • 647
  • 4
  • 14