1.新建一个实体类
package com.example.domain;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "device")
public class Device {
private String deviceIp;
private int deviceStatus;
public Device() {
}
public Device(String deviceIp) {
super();
this.deviceIp = deviceIp;
}
@XmlAttribute
public String getIp() {
return deviceIp;
}
public void setIp(String deviceIp) {
this.deviceIp = deviceIp;
}
@XmlAttribute
public int getStatus() {
return deviceStatus;
}
public void setStatus(int deviceStatus) {
this.deviceStatus = deviceStatus;
}
}
其中@XmlRootElement(name = "device")代表xml文件的根节点
@XmlAttribute代表xml文件的属性节点
在pom.xml文件中依赖下面2包
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-grizzly2-http</artifactId>
</dependency>
<!-- get JSON support: -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
<scope>test</scope>
</dependency>
</dependencies>
在服务类中编写
package com.example;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.example.domain.Device;
@Path("myresource")
public class MyResource {
@GET
@Produces({ MediaType.APPLICATION_JSON })
public Device getIt() {
Device d=new Device("1.1.1.1");
d.setStatus(2);
return d;
}
}
建立测试类:
package com.example;
import java.io.IOException;
import java.net.URI;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;
public class Main {
public static final String BASE_URI = "http://localhost:8080/myapp/";
public static HttpServer startServer() {
final ResourceConfig rc = new ResourceConfig().packages("com.example");
return GrizzlyHttpServerFactory.createHttpServer(URI.create(Main.BASE_URI), rc);
}
public static void main(String[] args) throws IOException {
final HttpServer server = Main.startServer();
}
}
启动后在浏览器中输入http://localhost:8080/myapp/myresource,页面返回
{"ip":"1.1.1.1","status":2}
返回json格式的数据。