3

I have a json string which looks like: {"a":5, "b":"asd", "c":"{\"d\":3}"} This can be deserialized to an object like:

class A {
   int a; // --> 5
   String b; // --> 'asd'
   String c; // --> '{"d":3}'
}

but i want it to be deserialized as:

class A {
   int a; // --> 5
   String b; // --> 'asd'
   MyClass c; // --> '{"d":3}'
}

where MyClass is:

class MyClass {
   int d; // --> 3
}

How can I achieve this in jackson during deserialization?

falcon
  • 1,332
  • 20
  • 39
  • 2
    You'd probably have to write a custom deserializer since Jackson won't be able to parse the escaped json for `c`. Ideally you'd get rid of the escaping - why do you have that in the first place? – Thomas Aug 24 '20 at 07:19
  • You could also have a look here: https://stackoverflow.com/questions/54531391/how-parse-nested-escaped-json-with-jackson – Thomas Aug 24 '20 at 07:21
  • 1
    as @thomas said, maybe you need change your serializer to {"a":5, "b":"asd", "c":{"d":3}} at first place. – andy Aug 24 '20 at 07:39

2 Answers2

2

I just found out that I can use the jackson converter:

public class MyClassConverter implements Converter<String, MyClass> {

  @Override
  public MyClass convert(String value) {
    try {
      return new ObjectMapper().readValue(value, MyClass.class);
    } catch (JsonProcessingException e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  public JavaType getInputType(TypeFactory typeFactory) {
    return typeFactory.constructSimpleType(String.class, null);
  }

  @Override
  public JavaType getOutputType(TypeFactory typeFactory) {
    return typeFactory.constructSimpleType(MyClass.class, null);
  }

}

And in the Bean:

class A {
   int a; 
   String b; 

   @JsonDeserialize(converter = MyClassConverter.class)
   MyClass c; 
}
falcon
  • 1,332
  • 20
  • 39
0

Try to do the deserialization twice:

A aObject = mapper.readValue(json,A.class);
aObject.setCObject(mapper.readValue(aObject.getC(),C.class));

class A {
    int a;
    String b;
    String c;
    C cObject;
}

class C {
    int d;
}
AMA
  • 408
  • 3
  • 9