无法将JSON对象解析为Springs Controller中的Java Object

时间:2014-05-17 05:06:50

标签: java json spring-mvc gson javabeans

我正在与这个JSON进行Java对象转换。这是我的客户端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代码中,来自客户端代码的字符串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 Value Objects(Java Bean)。但我无法做到。请帮忙。

1 个答案:

答案 0 :(得分:1)

创建类以保存两个POJO,说它是RequestCommand:

 class RequestCommand{

      private College college;

      private Address address;

      // follows getter and setter


  }

您的地址和学院POJO将自动被Spring Framework绑定到RequestCommand内的控制器方法Params,如下所示:

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

       command.getCollege();



}