简体   繁体   中英

Subclass as json parent object

I have a requirement where I need a subclass as object while creating a json payload.

EventBase

public class EventBase {
    @JsonProperty("event_id")
    private String id;
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

}

PaymentCapture (the sub class)

@JsonTypeName("resource")
public class PaymentCapture extends EventBase {
    @JsonProperty("parent_payment")
    private String parentPayment;

    public String getParentPayment() {
        return parentPayment;
    }

    public void setParentPayment(String parentPayment) {
        this.parentPayment = parentPayment;
    }
}

And I need a json payload in below form:

{
   "id": "someId",
   "resource": {
         "parent_payment": "23434"
  }
}

I can understand this violates inheritance relationship, but just want to know if there is any solution available or not.

The closest I could get when having similar problem was creating an adapter class. This solution prints one extra property which might be possible to be ignored if for example some inheritance was allowed but I assume that not and use just the declared classes in addition to the adapter, which is like:

@RequiredArgsConstructor
public class PaymentCaptureAdapterClass {
    @NonNull
    @JsonProperty
    private PaymentCapture resource;

    @JsonProperty
    private String getId() {
        return resource.getId();
    }
}

using this with code:

ObjectMapper om = new ObjectMapper();
om.enable(SerializationFeature.INDENT_OUTPUT);
PaymentCapture pc = new PaymentCapture();

pc.setId("someId");
pc.setParentPayment("23434");

log.info("\n{}", om.writeValueAsString(new AdapterClass(pc)));

prints something like:

{
  "resource" : {
    "event_id" : "someId",  // might be able to be ignored
    "parent_payment" : "23434"
  },
  "id" : "someId"
}

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