0

I am trying to return a set of product in magento 2 rest web api from the product repository. All working fine. But when I trying to return the result, the result is not in the form of a associative array. Following is the var_dump of the array before the return.

array(1) {
 ["product_categories"]=>
  array(3) {
    ["sale_items"]=>
    array(1) {
      [0]=>
      string(28) "array of items in sale items"
    }
    ["featured_items"]=>
    array(1) {
      [0]=>
      string(32) "array of items in featured_items"
    }
    ["new_style_items"]=>
    array(1) {
      [0]=>
      string(36) "array of items new_style_items items"
    }
  }
}

I am expecting the following result.

[
"product_categories": {
  "sale_items": [
    "array of items in sale items"
  ],
  "featured_items": [
    "array of items in featured_items"
  ],
  "new_style_items": [
    "array of items new_style_items items"
  ]
}
]

But I am receiving the following result.

[
{
"sale_items": [
  "array of items in sale items"
],
"featured_items": [
  "array of items in featured_items"
],
"new_style_items": [
  "array of items new_style_items items"
]
}
]

My php code is

$homePageProducts['product_categories'] = array ('sale_items' => array('array of items in sale items'),
                                                       'featured_items' => array('array of items in featured_items'),
                                                       'new_style_items' => array('array of items new_style_items items'));

    return $homePageProducts;

My return type is "mixed[]"

  • NOTE: your array is unexpectedly add another array in json , format you need to check you json is not create an array before you send – HAROONMIND Sep 13 '18 at 18:12
1

i think you cant return associative array in that way, you need implement service contracts. Please read the following post

and you may need to read people comments to, from Alan Kent

Service contracts do not support all types. You cannot use array() because we need to know what it is an array of, and associative array currently is not supported at all (we only support data interfaces which is serialized as a JSON object with name/value pairs.)

To expand, you cannot say “@return array”. You need to do something like “@return CustomerInterface[]”. You need to be explicit about the type of values in the array. Also we do not support associateArray” directly. You have to declare a data interface (one with setters/getters). Each setter/getter turns into a JSON object field (which is like keys of an associate array).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.