Java Spring MVC Rest中处理JSon时如何处理POJO嵌套对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18851361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:36:59  来源:igfitidea点击:

How to handle POJO nested objects when dealing with JSon in Spring MVC Rest

javajsonspringrestspring-mvc

提问by Alexio Cassani

I'm trying to figure out how to better deal with JSon serialization/deserialization of nested Java objects in Spring MVC.

我试图弄清楚如何更好地处理 Spring MVC 中嵌套 Java 对象的 JSon 序列化/反序列化。

My domain model is the following:

我的域模型如下:

  public class Cart {
        private String id;
        private Customer customerID;
        private Checkout checkoutID;
        private List<CartProduct> itemCatalogList;

        *** ... getters & setters ... ***


    }

   public class ProductCart {
        private String sku;
        private String color;
        private String sizeBase
        private int qty;

        *** ... getters & setters ... ***


    }

    public class Checkout {
        private String id;
        private String billingAddress;
        private String shippingAddress;
        private Cart cartID;

        *** ... getters & setters ... ***


    }

The JSon I was thinking is something like this:

我在想的 JSon 是这样的:

checkout:

查看:

{
  "cart": {
    "$oid": "51f631cb84812abb04000006"
  },

  "shippingAddress" : "5h avenue - new york",  
  "billingAddress" : "5h avenue - new york"
}

cart:

大车:

{
       "customer": {
      "$oid": "5174da574940368a9126e8dc"
      },
       "items_catalog": [
      {
        "sku": "00075161",
        "color": "ff99cc",
        "size_base": "IT_25",
        "qty": 3,
      },
      {
        "sku": "00075161",
        "color": "ff99cc",
        "size_base": "IT_27",
        "qty": 2,
      },
      {
        "sku": "00075161",
        "color": "ff99cc",
        "size_base": "IT_29",
        "qty": 1,
      }
}

Assuming this is a viable domain model & json document, how in Spring I could create a checkout starting from a JSon?

假设这是一个可行的域模型和 json 文档,我如何在 Spring 中创建从 JSon 开始的结帐?

My problem is that I don't know how to "explode" the $oid in the checkout & cart json in order to create checkout & cart Java Beans:

我的问题是我不知道如何“分解”结帐和购物车 json 中的 $oid 以创建结帐和购物车 Java Bean:

  • is there a way to do it automatically with Hymanson?

  • or should I create a sort of Interceptor to handle a, for example, checkout json in order to retrieve the cart and then perform the mapping to the POJO?

  • 有没有办法用Hyman逊自动做到这一点?

  • 或者我应该创建一种拦截器来处理例如结帐 json 以检索购物车然后执行到 POJO 的映射?

(- or there is a 3rd way?)

( - 或者有第三种方式?)

Thanks a lot for any advice.

非常感谢您的任何建议。

采纳答案by Ernestas Kardzys

If I understood you correctly, you could do something like this (I'm using Spring 3.2.3.RELEASE & Hymanson 1.9.12).

如果我理解正确,你可以做这样的事情(我使用的是 Spring 3.2.3.RELEASE & Hymanson 1.9.12)。

In your applicationContext.xml you have:

在你的 applicationContext.xml 你有:

<bean id="HymansonMessageConverter"
          class="org.springframework.http.converter.json.MappingHymansonHttpMessageConverter"/>

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="HymansonMessageConverter"/>
            </list>
        </property>
    </bean>

You have Spring controller which looks like this:

您有如下所示的 Spring 控制器:

package test;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/json")
public class JsonParsingController {
    private final static Logger log = Logger.getLogger(JsonParsingController.class);

    @RequestMapping(value = "/cart.do", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
@ResponseBody public CartResponse handleCart(@RequestBody Cart cart) {
    if (cart != null) {
        log.debug(cart);
    }

    return new CartResponse("OK!");
}
}

and three POJOs:

和三个 POJO:

package test;

public class Cart {
    private String id;
    private Checkout checkoutID;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Checkout getCheckoutID() {
        return checkoutID;
    }

    public void setCheckoutID(Checkout checkoutID) {
        this.checkoutID = checkoutID;
    }

    @Override
    public String toString() {
        return "Cart{" +
                "id='" + id + '\'' +
                ", checkoutID=" + checkoutID +
                '}';
    }
}

package test;

public class Checkout {
    private String id;
    private String billingAddress;
    private String shippingAddress;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getBillingAddress() {
        return billingAddress;
    }

    public void setBillingAddress(String billingAddress) {
        this.billingAddress = billingAddress;
    }

    public String getShippingAddress() {
        return shippingAddress;
    }

    public void setShippingAddress(String shippingAddress) {
        this.shippingAddress = shippingAddress;
    }

    @Override
    public String toString() {
        return "Checkout{" +
                "id='" + id + '\'' +
                ", billingAddress='" + billingAddress + '\'' +
                ", shippingAddress='" + shippingAddress + '\'' +
                '}';
    }
}

package test;

public class CartResponse {
    private String result;

    public CartResponse(String result) {
        this.result = result;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }
}

Then in your HTML page you can do something like this:

然后在您的 HTML 页面中,您可以执行以下操作:

<script language="JavaScript" type="text/javascript">
    $(document).ready(function () {
        // Your data
        var arr = {
                    id: '51f631cb84812abb04000006',
                    checkoutID: {
                        id: '123456789',
                        "shippingAddress" : "5h avenue - new york",
                        "billingAddress" : "5h avenue - new york"
                    }
                  };
        $.ajax({
            url: '/json/cart.do',
            type: 'POST',
            data: JSON.stringify(arr),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            async: false,
            success: function (msg) {
                alert(msg.result);
            }
        });
    });
</script>

At least as for me - it works :)

至少对我来说 - 它有效:)

回答by a_r_a_s

It's enough to return data structure (model) in controller file. JSON will be generate automatically based on structure in your model. Take a look here for example: http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/(section 3 - controller, and then, 5 - results)

在控制器文件中返回数据结构(模型)就足够了。JSON 将根据模型中的结构自动生成。看看这里的例子:http: //www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/(第3节 - 控制器,然后,5 - 结果)