0

Is there any way to convert a custom class eg: dw.customer.CustomerAddress to JSON format and return the value in a controller?

If I just return the attribute I'm receiving an empty object.

addresses

I know I can add each object value and return it, but I need a more automatic way to do that.

This is my code:

server.get('MyMethod', function (req, res, next) {
  var customerNo = req.querystring.customerNo;
  var profile;

  if (customerNo) {
    profile = CustomerMgr.searchProfile("customerNo = {0}", customerNo, true);
  }

  if (profile) {
    var addresses = [];

    if (!empty(profile.addressBook)) {
      profile.addressBook.addresses.toArray()
        .forEach((address) => {
          addresses.push(JSON.serialize(address));
        });
    }

    res.json({
      customerNo: profile.customerNo,
      addresses: addresses,
    });
  } else {
    res.json({
      errorCode: 404,
      errorMessage: "not found"
    });
  }

  delete res.viewData["action"];
  delete res.viewData["locale"];
  delete res.viewData["queryString"];

  next();
});
4
  • Did you try JSON.serialize() ? Commented May 31, 2022 at 23:16
  • @joacoiudica, I don't know how to use that. The project is headless, I'm currently editing an controller inside my cartridge, when I try to use JSON.serialize I get this error: TypeError: Cannot find function serialize in object [object JSON]. (*/cartridge/controllers/MyController.js)
    – waghcwb
    Commented Jun 1, 2022 at 12:36
  • please add the code you are currently running to get this problem Commented Jun 1, 2022 at 12:57
  • @joacoiudica, I've shared the code in the question.
    – waghcwb
    Commented Jun 1, 2022 at 13:10

1 Answer 1

2

Serialization does not work on "SFCC/Demandware" objects; you need to convert them to a model (Javascript Model Class) for serialization to JSON to work.

An example of such a model can be found here: https://github.com/SalesforceCommerceCloud/storefront-reference-architecture/blob/master/cartridges/app_storefront_base/cartridge/models/address.js

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .