使用Struts 2將Java對象序列化成JSON

Struts 2有個很強大的功能,就是可以自動完成服務器端Java對象和客戶端JSON對象之間的映射。這篇文章就介紹一下如何將Java對象序列化成JSON格式並傳到客戶端。可以看看不同的Java類型和JSON類型之間是如何映射的。

 

pom.xml

需要引入struts2-json-plugin包。

[html] view plaincopy
  1. <dependencies>  
  2.         <dependency>  
  3.             <groupId>org.apache.struts</groupId>  
  4.             <artifactId>struts2-core</artifactId>  
  5.             <version>2.3.12</version>  
  6.         </dependency>  
  7.         <dependency>  
  8.             <groupId>org.apache.struts</groupId>  
  9.             <artifactId>struts2-json-plugin</artifactId>  
  10.             <version>2.3.12</version>  
  11.         </dependency>  
  12.     </dependencies>  

struts.xml

package extends要增加”json-default”;負責映射的TestAction設置result type爲json。

[html] view plaincopy
  1. <package name="sandbox" namespace="/" extends=" struts-default, json-default">  
  2.         <action name="main" class="sandbox.z.MainAction">  
  3.             <result>/jsp/main.jsp</result>  
  4.         </action>  
  5. <action name="test" class="sandbox.z.TestAction">  
  6.             <result type="json" />  
  7.         </action>       
  8.     </package>  

main.jsp

[javascript] view plaincopy
  1. <script>  
  2.     require([ "dojo/ready",   
  3.               "dojo/_base/xhr",   
  4.               "dojo/json",  
  5.               "dijit/registry" ], function(ready, xhr, JSON, registry) {          
  6.         ready(function() {  
  7.             var xhrArgs = {  
  8.                 url : "/test.action",  
  9.                 handleAs : "json"/*設置返回數據的類型,和服務器端的設置一致*/  
  10.                 sync : true  
  11.             };  
  12.             var deferred = xhr.get(xhrArgs);  
  13.   
  14.             deferred.then(function(result) {  
  15.                 var output = JSON.stringify(result); /*將返回值變成json string*/  
  16.                 console.log(output); /*打印到Firebug console*/  
  17.             });  
  18.         });  
  19.     });  
  20. </script>  

TestAction.java

TestAction中,凡是有setter方法的屬性都會被轉換成JSON並輸出到客戶端。

[java] view plaincopy
  1. package sandbox.z;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import com.opensymphony.xwork2.ActionSupport;  
  9.   
  10. public class TestAction extends ActionSupport {  
  11.   
  12.     private static final long serialVersionUID = 1L;  
  13.   
  14.     private String name = "john";  
  15.     private int age = 30;  
  16.     private double height = 1.78;  
  17.     private int[] scores = {8590};  
  18.       
  19.     private List<Integer> score_array = new ArrayList<Integer>();  
  20.   
  21.     public void setScore_array(List<Integer> score_array) {  
  22.         this.score_array = score_array;  
  23.     }  
  24.   
  25.     public List<Integer> getScore_array() {  
  26.         return score_array;  
  27.     }  
  28.       
  29.     private List array = new ArrayList();  
  30.       
  31.     public List getArray() {  
  32.         return array;  
  33.     }  
  34.   
  35.     public void setArray(List array) {  
  36.         this.array = array;  
  37.     }  
  38.       
  39.     private Map books_map = new HashMap();  
  40.       
  41.     public void setBooks_map(Map books_map) {  
  42.         this.books_map = books_map;  
  43.     }  
  44.   
  45.     public Map getBooks_map() {  
  46.         return books_map;  
  47.     }  
  48.       
  49.     private Book book = new Book();  
  50.       
  51.     public void setBook(Book book) {  
  52.         this.book = book;  
  53.     }  
  54.       
  55.     public Book getBook() {  
  56.         return book;  
  57.     }  
  58.   
  59.     public String execute() {  
  60.         score_array.add(85);  
  61.         score_array.add(90);  
  62.           
  63.         array.add(85);  
  64.         array.add("Struts2");  
  65.           
  66.         books_map.put("struts2"85);  
  67.           
  68.         getBook().setName("Struts2");  
  69.         getBook().setPrice(85.30);  
  70.           
  71.         List<String> sellers = new ArrayList<String>();  
  72.         sellers.add("SA");  
  73.         sellers.add("SB");  
  74.         getBook().setSellers(sellers);  
  75.           
  76.         return SUCCESS;  
  77.     }  
  78.   
  79.     public void setName(String name) {  
  80.         this.name = name;  
  81.     }  
  82.   
  83.     public String getName() {  
  84.         return name;  
  85.     }  
  86.   
  87.     public void setAge(int age) {  
  88.         this.age = age;  
  89.     }  
  90.   
  91.     public int getAge() {  
  92.         return age;  
  93.     }  
  94.   
  95.     public void setHeight(double height) {  
  96.         this.height = height;  
  97.     }  
  98.   
  99.     public double getHeight() {  
  100.         return height;  
  101.     }  
  102.   
  103.     public void setscores(int[] scores) {  
  104.         this.scores = scores;  
  105.     }  
  106.   
  107.     public int[] getscores() {  
  108.         return scores;  
  109.     }  
  110.   
  111. }  

Firebug console

[html] view plaincopy
  1. {"age":30,"array":[85,"Struts2"],"book":{"name":"Struts2","price":85.3,"sellers":["SA","SB"]},"books_map":{"struts2":85},"height":1.78,"name":"john","score_array":[85,90],"scores":[85,90]  

總結

可以看到,從JAVA對象轉換到JSON格式還是非常直白的。由於JAVA對象比較複雜,表達能力強,而JSON格式比較簡單,表達能力弱,因此這種轉換大致不太會出錯。而相反的,如果要將JSON轉換成JAVA,則需要考慮是否需要額外的信息幫助將簡單的格式轉換成複雜對象。可以想象這中間會出現歧義。


參考文獻

[1] JSON Plugin. http://struts.apache.org/release/2.2.x/docs/json-plugin.html

原文地址:http://blog.csdn.net/eengel/article/details/8809618
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章