1. 首先实现相关接口
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import cn.com.chaser.gasalarm.utils.IOUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@Provider
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public final class GsonJsonProvider implements MessageBodyWriter
2. 修改web.xml配置
resteasy.scan.providers
true
resteasy.use.builtin.providers
false
3.读写JSON
@GET
@Path("/sysParams")
@Produces(MediaType.APPLICATION_JSON)
public SystemParameterRes getSystemParameters(
@HeaderParam("tokenId") final String tokenId) {
System.out.println("token:" + tokenId);
SystemParameterRes o = new SystemParameterRes();
o.setIntervalOfCheckMessage(300);
o.setIntervalOfUpdateData(500);
return o;
}
@POST
@Path("/login")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public LoginRes login(final User user) {
// get the configuration
CustomConfig.initConfig(sc);
LoginRes o = new LoginRes();
o.setName(user.getName());
// check logged or not
String userName = user.getName();
Entry entry = TokenDao.checkUserToken(userName);
if (entry != null) {
o.setToken(entry.getKey());
} else {
// create a new token
String token = IOUtils.generateToken(userName);
System.out.println("token:" + token);
UserToken userToken = new UserToken();
userToken.setName(userName);
userToken.setTimeout(System.currentTimeMillis());
userToken.setToken(token);
TokenDao.addToken(token, userToken);
o.setToken(token);
}
return o;
}
public class LoginRes {
private String token;
private String name;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class UserToken {
private String token;
private String name;
private long timeout;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getTimeout() {
return timeout;
}
public void setTimeout(long timeout) {
this.timeout = timeout;
}
}
public class User {
private String name;
private String password;
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}