Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 接口作为使用JAX-RS的GET返回方法_Java_Json_Web Services_Rest_Jax Rs - Fatal编程技术网

Java 接口作为使用JAX-RS的GET返回方法

Java 接口作为使用JAX-RS的GET返回方法,java,json,web-services,rest,jax-rs,Java,Json,Web Services,Rest,Jax Rs,下面的代码不遵循任何模式,我创建它只是为了说明问题 为GET方法定义的返回类型是接口,但具体类中的所有字段都是用JSON创建的 在下面的示例中,“anyThing”字段不属于IPerson接口,但是在JSON中生成结果时会考虑它,尽管方法的返回是IPerson接口 是这样吗 接口 public interface IPerson { int getId(); String getName(); } 混凝土类 import javax.ws.rs.Path; import j

下面的代码不遵循任何模式,我创建它只是为了说明问题

为GET方法定义的返回类型是接口,但具体类中的所有字段都是用JSON创建的

在下面的示例中,“anyThing”字段不属于IPerson接口,但是在JSON中生成结果时会考虑它,尽管方法的返回是IPerson接口

是这样吗

接口

public interface IPerson {

    int getId();
    String getName();

}
混凝土类

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

{"name":"Marcelo Ribeiro","anyThing":"Only for example","id":15}
应为JSON

{"name":"Marcelo Ribeiro","id":15}

序列化接口没有意义。反序列化是未知的。Json选择具体类型。如果需要,可以告诉它忽略特定字段

编辑


您必须考虑一个类可以实现多个接口。在这种情况下,json无法决定使用哪种接口方法序列化接口是没有意义的。反序列化是未知的。Json选择具体类型。如果需要,可以告诉它忽略特定字段

编辑


您必须考虑一个类可以实现多个接口。在这种情况下,json无法决定使用哪种接口方法

我注意到,创建json的过程首先标识字段,但为了获得值,使用了getter方法。我知道这似乎不太合理,但我理解,如果在确定要使用哪些getter方法之前,该机制将具体类转换为接口,那么会有一定的意义。我知道这在一开始似乎没有意义,所以我理解并感谢您的回答。您不能序列化无法实例化的类型,因此传递给json的不是接口,而是实例。在rest环境中返回接口也没有意义。Rest是关于传输状态的。您最好使用一个基本classI。我注意到,创建JSON的过程首先标识字段,但要获取值,则使用getter方法。我知道这似乎不太合理,但我理解,如果在确定要使用哪些getter方法之前,该机制将具体类转换为接口,那么会有一定的意义。我知道这在一开始似乎没有意义,所以我理解并感谢您的回答。您不能序列化无法实例化的类型,因此传递给json的不是接口,而是实例。在rest环境中返回接口也没有意义。剩下的是关于传输state的,最好使用基类