【问题标题】:Unable to parse JSON object to Java Object in Springs Controller无法在 Springs 控制器中将 JSON 对象解析为 Java 对象
【发布时间】:2014-05-17 05:06:49
【问题描述】:

我正在努力处理这种 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;
    }

这是映射到相应 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

}

所以我的问题是..我从客户端发送两个 JSON,即 Address, College,在我的控制器中,我试图将它们转换为各自的 >Java 值对象(Java Bean)。但我做不到。请帮忙。

【问题讨论】:

  • 客户端不应发送外部 json 对象,即。包含College 的那个。它应该只发送名为 College 的 JSON 对象。
  • {"collegeName": "sfd", "universityOrBoardName":"sdd","website":"fdd"} 是控制器所期望的。

标签: java json spring-mvc gson javabeans


【解决方案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();



}

【讨论】:

  • 你为什么这么认为,Address 来自哪里?
  • 可以@ModelAttribute反序列化json吗?
猜你喜欢
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多