The code below does not follow any pattern and was created by me just to illustrate the problem.
The return type defined for a GET method is an interface, but all fields in the concrete class are created in JSON.
In the example below, the "anyThing" field does not belong to the IPerson interface, however it is considered when producing the result in JSON, although the return of method is the IPerson interface.
Is this right?
Interface
public interface IPerson {
int getId();
String getName();
}
Concrete class
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/person")
public class PersonREST implements IPerson {
//IPerson implementation
private int id;
private String name;
@Override
public int getId() {
return this.id;
}
@Override
public String getName() {
return this.name;
}
//Other field not contained on IPerson
private String anyThing;
@GET
@Produces(MediaType.APPLICATION_JSON)
public IPerson get() {
//Set values on IPerson fields
this.id = 15;
this.name = "Marcelo Ribeiro";
//Set values on other fields, not contained on IPerson
this.anyThing = "Only for example";
System.out.println(this.anyThing);
//Here returned this instance converted on IPerson
return (IPerson) this;
}
}
JSON created
{"name":"Marcelo Ribeiro","anyThing":"Only for example","id":15}
JSON expected
{"name":"Marcelo Ribeiro","id":15}
Serializing an interface does not make sense. The deserialization is unknown. Json picks up the concrete type. You can tell it to ignore particular fields if you want.
edit
You have to take into consideration that a class can implement several interfaces. In that circumstance json can not make a decision of which interface methods to use
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.