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

时间:2013-09-17 13:33:39

标签: java json spring rest spring-mvc

我正在试图找出如何更好地处理Spring MVC中嵌套Java对象的JSon序列化/反序列化。

我的域名模型如下:

  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 ... ***


    }

我想的JSon是这样的:

结帐:

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

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

购物车:

{
       "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,
      }
}

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

我的问题是我不知道如何在结帐时“爆炸”$ oid&amp;购物车json为了创建结帐&amp;购物车Java Bean:

  • 有没有办法让杰克逊自动完成?

  • 或者我应该创建一种Interceptor来处理一个例如checkout json以便检索购物车然后执行到POJO的映射?

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

非常感谢任何建议。

2 个答案:

答案 0 :(得分:5)

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

在applicationContext.xml中,您有:

<bean id="jacksonMessageConverter"
          class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>

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

你有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!");
}
}

和三个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;
    }
}

然后在您的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>

至少对我而言 - 它有效:)

答案 1 :(得分:0)

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