JSON类型的参数与返回值,在客户端使用Ajax访问服务端时会非常有用。
加入:org.json.jar org.restlet.ext.json.jar 如果要用Jackson工具,就再加入org.codehaus.jackson.core.jar org.codehaus.jackson.mapper.jar org.restlet.ext.jackson.jar
一、返回简单Json类型
服务端
/**
* 返回简单JSON类型
*/
@Get
public Representation getMovieInfo() throws JSONException{
JSONObject mailEle = new JSONObject() ;
mailEle.put("name", "速度与激情6") ;
mailEle.put("size", 100000l) ;
mailEle.put("minutes", 120) ;
return new JsonRepresentation(mailEle) ;
}
使用restlet库开发客户端
@Test
public void test02() throws IOException, JSONException{
ClientResource client = new ClientResource("http://localhost:8888/");
//获取返回结果
Representation result = client.get() ;
JsonRepresentation jr = new JsonRepresentation(result);
JSONObject movie = jr.getJsonObject();
System.out.printf("name:%s size:%d minutes:%d" ,
movie.get("name") ,
movie.get("size"),
movie.get("minutes"));
}
二、接收简单Json类型
服务端:
/**
* 接收简单Json类型数据
*/
@Put
public String uploadMovie(JsonRepresentation mivieJson) throws JSONException{
JSONObject movie = mivieJson.getJsonObject();
String result = String.format("upload movie{name:%s size:%d minutes:%d} success!" ,
movie.get("name") ,
movie.get("size"),
movie.get("minutes"));
return result ;
}
使用restlet库开发客户端
@Test
public void test03() throws IOException, JSONException{
ClientResource client = new ClientResource("http://localhost:8888/json");
JSONObject mailEle = new JSONObject() ;
mailEle.put("name", "速度与激情6") ;
mailEle.put("size", 100000l) ;
mailEle.put("minutes", 120) ;
JsonRepresentation jr = new JsonRepresentation(mailEle);
Representation result = client.put(jr);
System.out.println(result.getText());
}
/**
* 将复杂对象使用Json格式返回
*/
@Get
public Representation getMovieInfo(){
Movie movie = new Movie() ;
movie.setName("速度与激情6");
movie.setSize(1000000l);
movie.setMinutes(120);
return new JacksonRepresentation(movie);
}
/**
* 将接收到的Json对象直接转换成java对象
* @param rp
* @return
* @throws IOException
*/
@Put
public String updateMovieInfo(Representation rp) throws IOException{
JacksonRepresentation movidRep = new JacksonRepresentation(rp , Movie.class);
Movie movie = movidRep.getObject() ;
String result = String.format("upload movie{name:%s size:%d minutes:%d} success!" ,
movie.getName() ,
movie.getSize(),
movie.getMinutes());
return result ;
}
Server的代码也发生了变化,为每个Resource分别绑定URI
public static void main(String[] args) throws Exception {
Component comp = new Component() ;
comp.getServers().add(Protocol.HTTP, 8888) ;
comp.getDefaultHost().attach("/json", MovieResourceJson.class) ;
comp.getDefaultHost().attach("/jackson", MovieResourceJackson.class) ;
comp.start();
}
然后如果是访问MovieResourceJackson.java中的get方法,需要访问http://localhost:8888/jackson
其他方法同上