Home > Software design >  Desrialzing JSON in spring boot, where a field is the combination of two fields
Desrialzing JSON in spring boot, where a field is the combination of two fields

Time:02-01

I have a controller with the following signiture:

public HttpEntity<RepresentationModel> confirmRegistration(@Valid @RequestBody RegistrationRequest request{}

the RegistrationRequest Json looks like this

{
//other fields
"countryCode":"44",
"mobileNumber": "07545878096"
}

I am trying to write a custom deserializer for this json

My mobileNumber class looks like this:

@Getter
@Setter
@EqualsAndHashCode
@ToString
@AllArgsConstructor
public class MobileNumber {
  @JsonProperty("mobilePhoneNumber")
  @JsonAlias("mobileNumber")
  String number;
  @JsonProperty(value = "countryCode", defaultValue = "44")
  String countryCode;
}

and a request object like so:

public class RegistrationRequest {
//other fields
  @JsonDeserialize(using = MobileNumberDeserializer.class)
  @MobileNumberValidator
  private final MobileNumber mobilePhoneNumber;

}

where the MobileNumberDeserializer looks like this:

public class ContactNumberDeserializer extends StdDeserializer<MobileNumber> {

  private static final long serialVersionUID = 1L;

  protected ContactNumberDeserializer() {
    super(MobileNumber.class);
  }


  @Override
  public MobileNumber deserialize(JsonParser jsonParser, DeserializationContext ctxt)
      throws IOException {

    JsonNode node = jsonParser.getCodec().readTree(jsonParser);
    String mobileNumber = "";
    if (node.has("mobilePhoneNumber")) {
      mobileNumber = node.get("mobilePhoneNumber").asText();
    } else if (node.has("phoneNumber")) {
      mobileNumber = node.get("phoneNumber").asText();
    } else if (node.has("mobileNumber")) {
      mobileNumber = node.get("mobileNumber").asText();
    }
    String countryCode = node.get("countryCode").asText();

    return new MobileNumber(mobileNumber, countryCode);

  }

when the ContactNumberDeserializer is invoked by the controller,jsonParser.getCodec().readTree(jsonParser); it's just the mobilePhoneNumber node and cant access countryCode.

CodePudding user response:

Quick check if ContactNumber and MobileNumber same classes.

Ideally it should be

public class ContactNumberDeserializer extends StdDeserializer<MobileNumber {

CodePudding user response:

In your MobileNumber class:

@Getter
@Setter
@EqualsAndHashCode
@ToString
@AllArgsConstructor
public class MobileNumber {
  @JsonProperty("mobilePhoneNumber")
  @JsonAlias("mobileNumber")
  String number;
  @JsonProperty("countryCode")
  String countryCode = "44";
}

Update JsonProperty annotation like above for countryCode. Hope it helps!

CodePudding user response:

You don't need to write ContactNumberDeserializer. If you wrote your class MobileNumber it would simply work.

  • Related