使用Struts 2将客户端JSON数据映射为服务器端Java对象

13 篇文章 0 订阅

上文(使用 Struts 2将Java对象序列化成JSON)介绍了如何将Java对象序列化成JSON格式并传到客户端。这篇文章就说说如何将客户端的JSON数据映射为服务器端的Java对象。

 

pom.xml

需要引入struts2-json-plugin包。

[html]  view plain copy
  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”;负责接收数据的SaveAction必须设置interceptor-ref为json。否则将无法得到客户端传来的数据。

[html]  view plain copy
  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.         <action name="save" class="sandbox.z.SaveAction">  
  9.             <interceptor-ref name="json">  
  10.                 <param name="contentType">application/json</param>  
  11.             </interceptor-ref>  
  12.             <result type="json" />  
  13.         </action>  
  14.     </package>  

main.jsp

[javascript]  view plain copy
  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 data = {  
  8.                     name: "john",  
  9.                     age: 30,  
  10.                     height: 1.78,  
  11.                     scores: [85, 90],  
  12.                     score_array: [85, 90],  
  13.                     array: [85,"Struts2"],  
  14.                     books_map: {  
  15.                         "struts2": 85  
  16.                     },  
  17.                     book: {  
  18.                         "name""Struts2",  
  19.                         "price": 85.3,  
  20.                         "sellers":[  
  21.                             "SA",  
  22.                             "SB"  
  23.                         ]  
  24.                     }  
  25.             };  
  26.               
  27.             var xhrArgs = {  
  28.                 url : "/save.action",  
  29.                 handleAs : "json",  
  30.                 contentType : 'application/json; charset=utf-8',  
  31.                 postData: dojo.toJson(data), /*data必须放在postData中,并转成json格式*/  
  32.                 sync : true  
  33.             };  
  34.             var deferred = xhr.post(xhrArgs);  
  35.   
  36.             /*服务器收到json数据,并转成相应的JAVA对象,最后依旧返回给客户端*/  
  37.             deferred.then(function(result) {  
  38.                 var output = JSON.stringify(result);  
  39.                 console.log(output);  
  40.             });  
  41.         });  
  42.     });  
  43. </script>  

SaveAction.java

SaveAction中,和客户端data中对应的属性会得到相应的数据。

[java]  view plain copy
  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 SaveAction extends ActionSupport {  
  11.   
  12.     private static final long serialVersionUID = 1L;  
  13.   
  14.     private String name;  
  15.     private int age;  
  16.     private double height;  
  17.     private int[] scores;  
  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.           
  61.         return SUCCESS;  
  62.     }  
  63.   
  64.     public void setName(String name) {  
  65.         this.name = name;  
  66.     }  
  67.   
  68.     public String getName() {  
  69.         return name;  
  70.     }  
  71.   
  72.     public void setAge(int age) {  
  73.         this.age = age;  
  74.     }  
  75.   
  76.     public int getAge() {  
  77.         return age;  
  78.     }  
  79.   
  80.     public void setHeight(double height) {  
  81.         this.height = height;  
  82.     }  
  83.   
  84.     public double getHeight() {  
  85.         return height;  
  86.     }  
  87.   
  88.     public void setscores(int[] scores) {  
  89.         this.scores = scores;  
  90.     }  
  91.   
  92.     public int[] getscores() {  
  93.         return scores;  
  94.     }  
  95.   
  96. }  

Firebug console

可以用FirebugConsole检验服务器端是否正确接收到数据了。

[html]  view plain copy
  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]}  

总结

正常情况下,从JSON到JAVA的转换也比较简单。关键是属性的名字和相应的数据类型符合转换的要求。

那当属性名字或数据类型不符合的时候,会产生什么样的问题呢?

 

1.      属性的数据类型不对

当JSON给相应的属性赋值时,若没有严格按照定义的数据类型赋值,则对于某些不匹配Struts2会进行自动转换。比如给String类型的赋了数值型的值,则该数值到服务器端后,会被转换成String类型。但如果对String类型的赋列表型的值,则会报错。

这儿还有一种取巧的办法,比如将JAVA的某个属性类型设成Object,则无论JSON中给这个属性赋什么值,服务器端都不会报错。不过这样一来,哪怕服务器端拿到这个属性值了,也很难将其映射到某个具体的数据类型上,并进行进一步的操作。因此最好还是定义比较严格的数据类型,并要求客户端JSON赋值时遵守数据类型的约定。



2.      属性少了

属性少了不会报错,而是相应的JAVA对象的属性值为null。

 

3.      属性多了

若在JSON中多了Action中未定义的属性,Action会直接忽视而不报错。



原文地址:http://blog.csdn.net/eengel/article/details/8813500

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值