繁体   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