xelamitchell
xelamitchell

Reputation: 522

Defining XML tag dynamically based on object property

I just can't get my head around this one.

I have an object called PermissionDto:

@XmlRootElement(name = "permission")
@XmlAccessorType(FIELD)
public class PermissionDto implements Serializable {

    private static final long serialVersionUID = 1L;

    private Link entity;

    ... some other properties, constructors and getters
}

This will produce the following JSON:

   {
       "entity":
       {
           "rel": "users",
           "href": ...
       }
    }

The entity rel can be (currently) "users" or "roles". What I would like would be to produce the following JSON when rel is "users":

   {
       "users":
       {
           "rel": "users",
           "href": ...
       }
    }

and when the rel is "roles":

   {
       "roles":
       {
           "rel": "roles",
           "href": ...
       }
    }

without having to create a UserPermissionDto and another RolePermissionDto considering they are exactly the same except for this one property. I can do entity.getRel() in order to know the rel of the Link.

Please note my server can also produce XML representations of these responses which means the tag for response

<entity rel="users" href="http://localhost:8080/users/1"/>

should also be represented as indicated above (either "users" or "roles" instead of "entity").

I use JAXB for XML and Jackson for JSON.

Any help is much appreciated.

Thanks

Upvotes: 1

Views: 63

Answers (2)

xelamitchell
xelamitchell

Reputation: 522

We actually turned the problem upside down and found a better solution.

We decided to try to implement our API in full HATEOAS fashion. In this way, users and roles are nothing more than links to those specific entities.

By using Spring HATEOAS Project PermissionDto was refactored to a PermissionResource which extends from ResourceSupport. This means a PermissionResource can be composed with either user or role URIs dependending on which Permission Resource Assembler is being used.

Upvotes: 1

lexicore
lexicore

Reputation: 43709

I'm not sure if this will work for JSON but try @XmlElements:

@XmlElements({
    @XmlElement(name="users", type=Users.class),
    @XmlElement(name="roles", type=Roles.class)
}
public Link entity;

This assumes Users and Roles extend Link. In this case, depending on whether your object has an instance of Users or Roles, you'll get users or roles element names. Not sure about JSON.

It may well be that this only works for collection properties.

Upvotes: 1

Related Questions