简体   繁体   中英

Desrialzing JSON in spring boot, where a field is the combination of two fields

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 .

Quick check if ContactNumber and MobileNumber same classes.

Ideally it should be

public class ContactNumberDeserializer extends StdDeserializer<MobileNumber {

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM