4

I have a class like below.

    public class MyDto {

    private int id;
    private String name;
    private String address;
    // getters and setters .....
    }

I have a MS4J service like below with returns a JSON from this object.

import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import org.example.service.dto.MyDto;
import org.wso2.msf4j.Request;

    @Path("/hello/1.[\\d]/version")
    public class HelloService {

        @GET
        @Path("/{version}")
        @Produces({"application/json"})
        public Response hello(@PathParam("version") int version, @Context Request request) {
            MyDto dtoObject = new MyDto(1, "TestObjName", "TestObjAddress");
            if (version < 1) {
                //return object without address
            } else {
                //return object with address
            }
        }
    }

At the runtime, I need to exclude properties from java class based on version. ie. if version >1 object without address else object with the address property.

Setting null for address field is not an option. I tried to do this with JacksonView and JacksonFilter yet unable to fit it to this scenario.

Any idea or sample code to fix this?

1 Answers1

1

You can create a subclass of MyDto with the proper annotation to ignore the property:

public class OldVersionDto extends MyDto
{
    @JsonIgnore
    protected String address;

    public OldVersionDto(int id, String name, String address) {
        super(id, name, address);
    }
}

it can even be an inner class of the service if it serves only ad-hoc purpose (just be sure to make it static). Now you instantiate the local variable according to the argument

        MyDto dtoObject;
        if (version < 1) {
            dtoObject = new MyDto(1, "TestObjName", "TestObjAddress");
        } else {
            dtoObject = new OldVersionDto(1, "TestObjName", "TestObjAddress");
        }

of course, the address property will have to be protected in the base class order for this to succeed.

Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47