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[]"

1
  • 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
    Commented Sep 13, 2018 at 18:12

1 Answer 1

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 and acknowledge you have read our privacy policy.

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