Jersey框架二:Jersey对JSON的支持

来源:互联网 发布:python .write 编辑:程序博客网 时间:2024/05/16 11:38

Jersey系列文章:

Jersey框架一:Jersey RESTful WebService框架简介

Jersey框架二:Jersey对JSON的支持

Jersey框架三:Jersey对HTTPS的支持

 

Jersey提供3种基本方式来使用JSON格式

无论使用何种方式,在原有包的基础上,都需要在客户端和服务端Maven配置文件中添加jersey-json包以支持JSON格式

[html] view plain copy
  1. <dependency>  
  2.     <groupId>com.sun.jersey</groupId>  
  3.     <artifactId>jersey-json</artifactId>  
  4.     <version>1.18</version>  
  5. </dependency>  

一,基于POJO

Request类和Response类(服务端和客户端都需要)都是基本的POJO:

[java] view plain copy
  1. package com.sean;  
  2.   
  3. public class Request {  
  4.     private String query;  
  5.   
  6.     public String getQuery() {  
  7.         return query;  
  8.     }  
  9.   
  10.     public void setQuery(String query) {  
  11.         this.query = query;  
  12.     }  
  13. }  
[java] view plain copy
  1. package com.sean;  
  2.   
  3. public class Response {  
  4.     private int respCode;  
  5.     private String respDesc;  
  6.       
  7.     public int getRespCode() {  
  8.         return respCode;  
  9.     }  
  10.       
  11.     public void setRespCode(int respCode) {  
  12.         this.respCode = respCode;  
  13.     }  
  14.       
  15.     public String getRespDesc() {  
  16.         return respDesc;  
  17.     }  
  18.       
  19.     public void setRespDesc(String respDesc) {  
  20.         this.respDesc = respDesc;  
  21.     }  
  22. }  

服务端代码:

[java] view plain copy
  1. package com.sean;  
  2.    
  3. import java.io.IOException;  
  4. import java.net.URI;  
  5.   
  6. import javax.ws.rs.Consumes;  
  7. import javax.ws.rs.POST;  
  8. import javax.ws.rs.Path;  
  9. import javax.ws.rs.Produces;  
  10. import javax.ws.rs.core.MediaType;  
  11. import javax.ws.rs.core.UriBuilder;  
  12.   
  13. import org.glassfish.grizzly.http.server.HttpServer;  
  14.   
  15. import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;  
  16. import com.sun.jersey.api.core.PackagesResourceConfig;  
  17. import com.sun.jersey.api.core.ResourceConfig;  
  18. import com.sun.jersey.api.json.JSONConfiguration;  
  19.    
  20. @Path("query")   
  21. public class MyResource {  
  22.       
  23.     @POST  
  24.     @Consumes(MediaType.APPLICATION_JSON)  
  25.     @Produces(MediaType.APPLICATION_JSON)  
  26.     public Response query(Request req) {  
  27.         System.out.println(req.getQuery());  
  28.           
  29.         Response resp = new Response();  
  30.         resp.setRespCode(0);  
  31.         resp.setRespDesc(req.getQuery());  
  32.         return resp;  
  33.     }  
  34.       
  35.     public static void main(String[] args) {  
  36.         URI uri = UriBuilder.fromUri("http://127.0.0.1").port(10000).build();  
  37.         ResourceConfig rc = new PackagesResourceConfig("com.sean");  
  38.         //使用Jersey对POJO的支持,必须设置为true  
  39.          rc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true);  
  40.         try {  
  41.             HttpServer server = GrizzlyServerFactory.createHttpServer(uri, rc);  
  42.             server.start();  
  43.         } catch (IllegalArgumentException e) {  
  44.             e.printStackTrace();  
  45.         } catch (NullPointerException e) {  
  46.             e.printStackTrace();  
  47.         } catch (IOException e) {  
  48.             e.printStackTrace();  
  49.         }  
  50.         try {  
  51.             Thread.sleep(1000*1000);  
  52.         } catch (InterruptedException e) {  
  53.             e.printStackTrace();  
  54.         }  
  55.     }  
  56. }  

客户端代码:

[java] view plain copy
  1. package com.sean;  
  2.   
  3. import javax.ws.rs.core.MediaType;  
  4.   
  5. import com.sun.jersey.api.client.Client;  
  6. import com.sun.jersey.api.client.ClientResponse;  
  7. import com.sun.jersey.api.client.WebResource;  
  8. import com.sun.jersey.api.client.config.ClientConfig;  
  9. import com.sun.jersey.api.client.config.DefaultClientConfig;  
  10. import com.sun.jersey.api.json.JSONConfiguration;  
  11.   
  12. public class JerseyClient {  
  13.   
  14.     public static void main(String[] args) {  
  15.         ClientConfig cc = new DefaultClientConfig();  
  16.         //使用Jersey对POJO的支持,必须设置为true  
  17.         cc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);  
  18.         Client client = Client.create(cc);  
  19.           
  20.         WebResource resource = client.resource("http://127.0.0.1:10000/query");  
  21.           
  22.         Request req = new Request();  
  23.         req.setQuery("name");  
  24.           
  25.         ClientResponse response = resource  
  26.                 .accept(MediaType.APPLICATION_JSON)  
  27.                 .type(MediaType.APPLICATION_JSON)  
  28.                 .post(ClientResponse.class, req);  
  29.           
  30.         Response resp = response.getEntity(Response.class);  
  31.         System.out.println(resp.getRespCode() + " " + resp.getRespDesc());  
  32.     }  
  33. }  

 

二,基于JAXB

使用JAXB的优点在于,无论使用XML格式还是JSON格式数据,都可以使用统一的Java模型

缺点很难找到一个合适的方式来生成特殊的JSON格式,这也是Jersey提供很多控制选项的原因

将Request类和Response类进行修改:

[java] view plain copy
  1. package com.sean;  
  2.   
  3. import javax.xml.bind.annotation.XmlRootElement;  
  4.   
  5. @XmlRootElement  
  6. public class Request {  
  7.     private String query;  
  8.   
  9.     public String getQuery() {  
  10.         return query;  
  11.     }  
  12.   
  13.     public void setQuery(String query) {  
  14.         this.query = query;  
  15.     }  
  16. }  
[java] view plain copy
  1. package com.sean;  
  2.   
  3. import javax.xml.bind.annotation.XmlRootElement;  
  4.   
  5. @XmlRootElement  
  6. public class Response {  
  7.     private int respCode;  
  8.     private String respDesc;  
  9.       
  10.     public int getRespCode() {  
  11.         return respCode;  
  12.     }  
  13.       
  14.     public void setRespCode(int respCode) {  
  15.         this.respCode = respCode;  
  16.     }  
  17.       
  18.     public String getRespDesc() {  
  19.         return respDesc;  
  20.     }  
  21.       
  22.     public void setRespDesc(String respDesc) {  
  23.         this.respDesc = respDesc;  
  24.     }  
  25. }  

服务端代码去掉下面的配置

[java] view plain copy
  1. //       rc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true);  

客户端代码去掉下面的配置

[java] view plain copy
  1. //      cc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);  

Jersey提供很多控制选项以便更精细的控制JSON的解析、组装过程,但是就我个人来看,JAXB提供的标签足够使用了

 

三,基于底层JSONObject/JSONArray

最大的优势在于可以完全控制JSON的解析、组装过程,相应的,在处理数据对象时也要更复杂

服务端代码如下:

[java] view plain copy
  1. package com.sean;  
  2.    
  3. import java.io.IOException;  
  4. import java.net.URI;  
  5.   
  6. import javax.ws.rs.Consumes;  
  7. import javax.ws.rs.POST;  
  8. import javax.ws.rs.Path;  
  9. import javax.ws.rs.Produces;  
  10. import javax.ws.rs.core.MediaType;  
  11. import javax.ws.rs.core.UriBuilder;  
  12.   
  13. import org.codehaus.jettison.json.JSONException;  
  14. import org.codehaus.jettison.json.JSONObject;  
  15. import org.glassfish.grizzly.http.server.HttpServer;  
  16.   
  17. import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;  
  18. import com.sun.jersey.api.core.PackagesResourceConfig;  
  19. import com.sun.jersey.api.core.ResourceConfig;  
  20.    
  21. @Path("query")   
  22. public class MyResource {  
  23.       
  24.     @POST  
  25.     @Consumes(MediaType.APPLICATION_JSON)  
  26.     @Produces(MediaType.APPLICATION_JSON)  
  27.     public JSONObject query(JSONObject query) {  
  28.         //{"query":"name"}  
  29.         System.out.println(query.toString());  
  30.           
  31.         JSONObject resp = new JSONObject();  
  32.         try {  
  33.             resp.put("respCode"0);  
  34.             resp.put("respDesc", query.get("query"));  
  35.         } catch (JSONException e) {  
  36.             e.printStackTrace();  
  37.         }  
  38.         return resp;  
  39.     }  
  40.       
  41.     public static void main(String[] args) {  
  42.         URI uri = UriBuilder.fromUri("http://127.0.0.1").port(10000).build();  
  43.         ResourceConfig rc = new PackagesResourceConfig("com.sean");  
  44.         try {  
  45.             HttpServer server = GrizzlyServerFactory.createHttpServer(uri, rc);  
  46.             server.start();  
  47.         } catch (IllegalArgumentException e) {  
  48.             e.printStackTrace();  
  49.         } catch (NullPointerException e) {  
  50.             e.printStackTrace();  
  51.         } catch (IOException e) {  
  52.             e.printStackTrace();  
  53.         }  
  54.         try {  
  55.             Thread.sleep(1000*1000);  
  56.         } catch (InterruptedException e) {  
  57.             e.printStackTrace();  
  58.         }  
  59.     }  
  60. }  

客户端代码如下:

[java] view plain copy
  1. package com.sean;  
  2.   
  3. import javax.ws.rs.core.MediaType;  
  4.   
  5. import org.codehaus.jettison.json.JSONException;  
  6. import org.codehaus.jettison.json.JSONObject;  
  7.   
  8. import com.sun.jersey.api.client.Client;  
  9. import com.sun.jersey.api.client.ClientResponse;  
  10. import com.sun.jersey.api.client.WebResource;  
  11. import com.sun.jersey.api.client.config.ClientConfig;  
  12. import com.sun.jersey.api.client.config.DefaultClientConfig;  
  13.   
  14. public class JerseyClient {  
  15.   
  16.     public static void main(String[] args) {  
  17.         ClientConfig cc = new DefaultClientConfig();  
  18.         Client client = Client.create(cc);  
  19.           
  20.         WebResource resource = client.resource("http://127.0.0.1:10000/query");  
  21.           
  22.         JSONObject req = new JSONObject();  
  23.         try {  
  24.             req.put("query""name");  
  25.         } catch (JSONException e) {  
  26.             e.printStackTrace();  
  27.         }  
  28.           
  29.         ClientResponse response = resource  
  30.                 .accept(MediaType.APPLICATION_JSON)  
  31.                 .type(MediaType.APPLICATION_JSON)  
  32.                 .post(ClientResponse.class, req);  
  33.           
  34.         JSONObject resp = response.getEntity(JSONObject.class);  
  35.         //{"respCode":0,"respDesc":"name"}  
  36.         System.out.println(resp.toString());  
  37.     }  
  38. }  

与JAXB相比,结果是相同的,但是处理过程(主要是组装JSON对象)要复杂

对于上面3种方式,均可使用String类代替Request类、Response类或JSONObject类,Jersey会自动将对象转换为JSON串

当然,如果客户端修改为String,服务端也要相应的修改为String类型

修改客户端代码:

[java] view plain copy
  1. public class JerseyClient {  
  2.   
  3.     public static void main(String[] args) {  
  4.         ClientConfig cc = new DefaultClientConfig();  
  5.         Client client = Client.create(cc);  
  6.           
  7.         WebResource resource = client.resource("http://127.0.0.1:10000/query");  
  8.           
  9.         JSONObject req = new JSONObject();  
  10.         try {  
  11.             req.put("query""name");  
  12.         } catch (JSONException e) {  
  13.             e.printStackTrace();  
  14.         }  
  15.           
  16.         String response = resource  
  17.                 .accept(MediaType.APPLICATION_JSON)  
  18.                 .type(MediaType.APPLICATION_JSON)  
  19.                 .post(String.class, req.toString());  
  20.     }  
  21. }  

 

0 0