3

Given these to models (using Lombok @Data for simplicity)

@Data
public class RootModel {
    private Integer myRootProperty;
    private SubModel mySubModel;
}

@Data
public class SubModel {
    private Integer mySubProperty
}

and this JSON-String:

{
    "myRootProperty" : 5,
    "mySubModel" : "{ "mySubProperty" : 3 }"
}

Is it possible (via Jackson-Annotations) to directly deserialze the embedded JSON-String (which origins from a DB-Column) to its Java-POJO-Model?

Background is that we need a JSON-Formatted configuration in our DB and I want to handle it typesafe as soon as possible - ideally directly after deserialization.

Marko Previsic
  • 1,820
  • 16
  • 30
angrybobcat
  • 268
  • 1
  • 10

3 Answers3

0

Yes, it sure is. Just annotate with the @JsonProperty tag

@Data
public class RootModel {
    @JsonProperty("myRootProperty")
    private Integer myRootProperty;

    @JsonProperty("mySubModel")
    private SubModel mySubModel;
}

@Data
public class SubModel {
    @JsonProperty("mySubProperty")
    private Integer mySubProperty
}

Then use the object mapper to deserialise into the POJO

RootModel rootModel = objectMapper.readValue(jsonString, RootModel.class);
stringy05
  • 6,511
  • 32
  • 38
  • If I do this, I get an Exception: Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `SubModel` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{"mySubProperty": 3}') Please note that the JSON is Embedded as String into the Input-Json - I guess I need something like a "Json-String-Constructor" (or alike) in SubModel... – angrybobcat Jul 31 '19 at 07:10
  • oh right, this is a Jackson vs Lombok thing, where Lombok is creating a constructor that is affecting how Jackson uses default constructors. check out this answer: https://stackoverflow.com/questions/39381474/cant-make-jackson-and-lombok-work-together, there's probably a few of these strategies that will work – stringy05 Aug 01 '19 at 00:55
0

The problem lies with your Json string. If you take a look at your Json,

{
    "myRootProperty" : 5,
    "mySubModel" : "{ "mySubProperty" : 3 }"
}

The subnode is enclosed in "" like "{ "mySubProperty" : 3 }" which will be considered as it is a value. Instead if your Json is like as specified below (Note:I only removed the double quotes) like { "mySubProperty" : 3 }, deserialization won't complain any more. Your typical Json string would look like specified below.

{
    "myRootProperty" : 5,
    "mySubModel" : { "mySubProperty" : 3 }
}
Coder
  • 2,153
  • 1
  • 16
  • 21
0

No there is no automated way to do that. You could try a custom deserializer. Otherwise read it as just string and convert that to Typed Object in another step.

so-random-dude
  • 15,277
  • 10
  • 68
  • 113