2014-05-17 113 views
0

我正在甩這個JSON轉換爲Java對象。這是我的客戶端JavaScript代碼,它將JSON發送到Ajax調用。無法將JSON對象解析爲彈簧控制器中的Java對象

var college = { 
     collegeName : $("#collegeNameID").val(), 
     estYear : $("#estYear").val(), 
     universityOrBoardName : $("#university").val(), 
     website : $("#webSite").val() 
    }; 
    var address = { 
     city : $("#cityID").val(), 
     district: $("districtID").val() 
    }; 
    ajaxResult = $.ajax({ 
     url : urls, 
     async : false, 
     cache : false, 
     type : "POST", 
     dataType : "json", 
     contentType : "application/json", 
     mimeType : "application/json", 
     data : JSON.stringify({ College : college, Address: address}), 
     mimeType : "application/json", 
     success : function(result) { 
     return result; 
    } 

這裏是一個被映射到相應的JSON我的POJO類。

Address.java

private String district; 
private String city; 
    (there are other member variables for which I will not be getting the input from the Client side. I will be setting those in server side) 

College.java

private String collegeName; 
private String universityOrBoardName; 
private String website; 
    (there are other member variables for which I will not be getting the input from the Client side. I will be setting those in server side) 

在我的控制器代碼中,JSON字符串值從客戶端代碼來是

{"College":{"collegeName":"sfd","universityOrBoardName":"sdd","website":"fdd"}} 

我的控制器代碼

CollegeController.java

@RequestMapping(value="/submitCol", method = RequestMethod.POST) 
    public String mycollege(@RequestBody String str,HttpServletRequest req) 
    { 
      Gson gson=new Gson(); 
    Type type = new TypeToken<College>(){}.getType(); 
    College cols=gson.fromJson(str, type); 
    System.out.println("College Name "+cols.getCollegeName());//HERE ITS PRINTING NULL 

} 

所以我的問題is..I我發送兩個JSONs地址,學院從客戶端和在我的控制,我想將它們轉換成它們各自的Java值對象(Java Bean)。但我無法做到。請幫忙。

+1

的客戶端不應該發送外部json對象,即。包含'College'的那個。它只應該發送名爲'College'的JSON對象。 –

+0

'''「collegeName」:「sfd」,「universityOrBoardName」:「sdd」,「website」:「fdd」}控制器期望的是''''。 – Misha

回答

1

創建類同時容納POJO的說,它可以RequestCommand:

class RequestCommand{ 

     private College college; 

     private Address address; 

     // follows getter and setter 


    } 

您的地址和學院POJO將自動內RequestCommand被綁定通過Spring框架控制器方法PARAMS象下面這樣:

@RequestMapping(value="/submitCol", method = RequestMethod.POST) 
public String mycollege(@ModelAttribute RequestCommand command) 
{ 
     // use both of them here 

     command.getCollege(); 



} 
+0

你爲什麼這麼認爲,「地址」從哪裏來? –

+0

增加RequestCommand來保存地址 –

+0

可以'@ ModelAttribute'反序列化json嗎? –