Attila Molnár
Attila Molnár

Reputation: 39

JacksonXML: Resolve inconventional json field name without annotation

I have a java project where one of my packages contain a lot of dataclasses. These classes are used with deserialization. Currently the package depends on fasterXML only because one of my classes has this field:

String eMail;

I would like to remove the dependency to fasterXML but I have the following problem.

val mapper = new ObjectMapper();
  
// Produces UnrecognizedPropertyException: Unrecognized field "eMail" 
// because by default it expects eMail with a lower case 'm'
val res1 = mapper.readValue("{\"eMail\":\"asd\"}", PP.class);
  
// BTW this Produces '{"email":"asd"}'  --> 'm' in eMail is lower case!
val res2 = mapper.writeValueAsString(new PP() {{setEMail("asd");}});

Where the PP class is

@Getter
@Setter
private static class PP {
    private String eMail;
}

I CANNOT change the json format!

Is it possible to somehow correctly readValue(PP) without using the JsonProperty annotation? Maybe configuring the objectMapper somehow? The only field I have problem is this one. :(

Thanks!

Upvotes: 0

Views: 82

Answers (1)

ellis
ellis

Reputation: 126

You could make an intermediate class

@Getter
@Setter
private static class IntermediatePP {
    private String email;

    public PP convert() {
        PP output = new PP();
        output.setEMail(this.email);
        return output
    }
}

Then change your code to

val res1 = mapper.readValue("{\"eMail\":\"asd\"}",
                     IntermediatePP.class).convert();

Upvotes: 1

Related Questions