0

I have a json webservice I'm calling with a spring rest template. One of the request parameters is an interface. I'm looking for the right combination of annotations (either Jackson or Jaxb) that will create my json request.

My request needs to look like this:

{
    "request": {
        "specificAccountIdentifier": {
            "field1" : "value",
            "field2" : "value"
        }
    }
}

However, right now, it's marshaling as this:

{
    "request": {
        "accountIdentifier": {
            "field1" : "value",
            "field2" : "value"
        }
    }
}

Request Class:

@XmlRootElement
@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
public class Request {
    @XmlAnyElement
    @XmlElementRefs({@XmlElementRef(type = SpecificAccountIdentifier.class)})
    private AccountIdentifier accountIdentifier;

    public Request() {
    }
}

AccountIdentifier:

@XmlSeeAlso(SpecificAccountIdentifier.class)
public interface AccountIdentifier extends Serializable {
}

SpecificAccountIdentifier:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
@XmlType
public class SpecificAccountIdentifier implements AccountIdentifier {
    private static final long serialVersionUID = 8894475816041559L;
    private Long field1;
    private Long field2;
    ...class details...
}

I've tried a few different combinations of @JsonTypeInfo, but can't get anything to work right.

UPDATE:

Even after looking into the answer below, I still could not get anything to work, so I ended up just writing my own custom Serializer.

  • should you be renaming private AccountIdentifier accountIdentifier; to private AccountIdentifier specificAaccountIdentifier? – johnII Dec 27 '17 at 22:22
  • I would, but there will be multiple implementations for this eventually, so just changing the variable name won't work. – draconswan Dec 27 '17 at 22:25
  • you mean this "specificAccountIdentifier" is something dynamic depending on which implementation? – johnII Dec 27 '17 at 22:29
  • yes, the accountIdentifier variable can be of a few different types, and I'm looking for an annotation that will use the implementation class name as the json field name instead of the interface variable name. – draconswan Dec 27 '17 at 22:31

1 Answers1

0

Found similar question asked 4 years ago but it seems you can use it to kick start the idea behind.

Basically it is using EclipseLink JAXB (MOXy) and a factory method to generate the Implementation of your interface.

https://stackoverflow.com/a/16155520/6039974

johnII
  • 1,423
  • 1
  • 14
  • 20