Search code examples
javajsonrestbroadleaf-commerce

How do I format JSON for Broadleaf Commerce REST API - Wrapper is members are null?


I created a new path on the Catalog Endpoint. It is suppose to accept a JSON representation of a Product and add it to the database.

public ProductWrapper insertProduct(HttpServletRequest request, ProductWrapper wrapper)
{
    return wrapper;
}


@RequestMapping(value="product",method=RequestMethod.POST)
public ProductWrapper addProduct(HttpServletRequest request, ProductWrapper wrapper){
    return insertProduct(request, wrapper);
}

But when I put the JSON in the body of the message. It is not saving it into my wrapper. My JSON looks like this :

{
  "id": 1,
  "name": "Sudden Death Sauce",
  "longDescription": "As my Chilipals know, I am never one to be satisfied. Hence, the creation of Sudden Death. When you need to go beyond... Sudden Death will deliver! ",
  "retailPrice": {
    "amount": "10.99",
    "currency": "USD"
  },
  "primaryMedia": {
    "id": 101,
    "title": "Sudden Death Sauce Bottle",
    "url": "/cmsstatic/img/sauces/Sudden-Death-Sauce-Bottle.jpg",
    "altText": "primary"
  },
  "active": true,
  "activeStartDate": "2017-01-25T16:32:36.993-0500",
  "manufacturer": "Blair's",
  "defaultCategoryId": 2002,
  "productAttribute": [
    {
      "id": 1,
      "productId": 1,
      "attributeName": "heatRange",
      "attributeValue": "4"
    }
  ],
  "media": [
    {
      "id": 102,
      "title": "Sudden Death Sauce Close-up",
      "url": "/cmsstatic/img/sauces/Sudden-Death-Sauce-Close.jpg",
      "altText": "alt1"
    },
    {
      "id": 101,
      "title": "Sudden Death Sauce Bottle",
      "url": "/cmsstatic/img/sauces/Sudden-Death-Sauce-Bottle.jpg",
      "altText": "primary"
    }
  ]
}

Am I missing anything? I put a breakpoint and it hits it fine. The wrapper is instantiated but all the members are null.


Solution

  • You need to annotate the wrapper parameter with @RequestBody and also add an accepts on your @RequestMapping:

    @RequestMapping(value="product",method=RequestMethod.POST, accepts="application/json")
    public ProductWrapper addProduct(HttpServletRequest request, @RequestBody ProductWrapper wrapper){
        return insertProduct(request, wrapper);
    }
    

    When you send your request, make sure you send a Content-Type header as well, like Content-Type=application/json so that Spring will serialize it appropriately.