3
votes

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

1
May be this could help: stackoverflow.com/a/24864724/5819195 - jarvo69
nope. the other question is about deserializing to List<Country> and i need a String without any deserialization - piotrek

1 Answers

7
votes

@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;