json - 如何在 Spring MVC 中将字符串转换为对象

标签 json spring-mvc jackson gson converters

我需要用一个提交按钮提交两个表单,所以我做了JS函数:

var submitAllForms = function(){
    var paymentForm = $("#paymentsDetailsForm").serialize();
    var orderForm = $("#orderForm").serialize();
        $.ajax({
          method: "post",
          url: "/order",
          dataType: 'json',
          data: { paymentsDetailsForm : JSON.stringify(paymentForm), orderForm : JSON.stringify(orderForm) },
          success: alert('form has been sent')
        });
}

这是我的表格:

@Data
public class PaymentDetailsForm  implements Serializable {

    private Date storageDate;
    private String paymentMethod;
    ...
}

@Data
public class OrderForm implements Serializable {

    private String company;
    private String sizeOfMove;
    ... 
}

这是我的 Controller :

    @RequestMapping(value = "/order", method = RequestMethod.POST)
    public ModelAndView handleOrder(String paymentsDetailsForm, String orderForm) {
        // How to cast paymentsDetailsForm to PaymentsDetailsForm
        // How to cast orderFormto OrderForm
        ModelAndView model = new ModelAndView();
        model.addObject("paymentsDetailsForm", new PaymentDetailsForm());

        model.setViewName("/order");
        return model;
    }

}

因此在 Controller 中,参数“orderForm”如下所示:“company=ROYAL_MOVING&sizeOfMove=STUDIO...”

如何将字符串参数转换为 OrderForm 和 PaymentsDetailsForm?或者这个问题(用一种方法提交和处理多个表单)可以通过另一种方式解决?

最佳答案

这是一个 JSON 字符串,所以不用担心。您可以在 Google 中搜索,因为有很多方法可以将 JSON 字符串反序列化为对象。

另一种方法是,首先从 & 符号中分割字符串,然后再次从 = 符号中分割每个组,现在您可以在循环中将这些值与对象映射。

关于json - 如何在 Spring MVC 中将字符串转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38422221/

相关文章:

json - Jaxb json缺少一个元素数组的括号

json - Swift:在for循环中打印来自JSON的不同类型(枚举)的变量

spring - 扩展 RepositoryRestExceptionHandler

java - @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) 不工作

javascript - JSON 字符串结果的 ejs <%= 和encodeURI 有什么区别?

c# - .net 核心 : Invalid property identifier character: {. 路径 'Logging',第 10 行,位置 2。Newtonsoft.Json.JsonTextReader.ParseProperty()

spring-mvc - Spring 安全 : Why is my custom AccessDecisionVoter not invoked

java - 如何在 Spring MVC 中调用 Controller 方法

java - 反序列化时动态绑定(bind)JsonProperty

java - 如何阻止 Jackson JSON 映射器隐式转换为字符串?