簡體   English   中英

無法在Springs Controller中將JSON對象解析為Java對象

[英]Unable to parse JSON object to Java Object in Springs Controller

我正在努力將JSON轉換為Java Object。 這是我的客戶端JavaScript代碼,它將JSON發送到Ajax調用。

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;
    }

這是我的Pojo類,它們映射到相應的JSON。

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)

在我的Controller代碼中,來自Client代碼的字符串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

}

所以我的問題是..我正在從客戶端發送兩個JSON,地址,大學 ,並且在我的控制器中,我試圖將它們轉換為各自的Java值對象(Java Beans) 但是我做不到。 請幫忙。

創建Class來保存兩個POJO都說是RequestCommand:

 class RequestCommand{

      private College college;

      private Address address;

      // follows getter and setter


  }

Spring Framework會自動將您的地址和College POJO綁定到RequestCommand中,並綁定到控制器方法,如下所示:

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

       command.getCollege();



}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM