Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

json serialization #65

Closed
gmhafiz opened this issue Sep 21, 2022 · 2 comments
Closed

json serialization #65

gmhafiz opened this issue Sep 21, 2022 · 2 comments

Comments

@gmhafiz
Copy link

gmhafiz commented Sep 21, 2022

Using laravel, it can automatically serialize array or object into json. For example

class IndexController extends Controller
{
  public function index()
  {
    return ['amount' => 0.1, 'currency' => 'AUD'];
  }
}

becomes

{"amount":0.1,"currency":"AUD"}

However, if laravel is returning brick/money, it returns an empty object:

class IndexController extends Controller
{
  public function index()
  {
    return new Money::of(0.1,'AUD');
  }
}

becomes

{}

How do you make it to serialize into {"amount":0.1,"currency":"AUD"} response instead?

Other way I can think of is to implement JsonSerializable and implement jsonSerialize() function:

final class Money extends AbstractMoney implements JsonSerializable
{
    ...

    public function jsonSerialize(): array
    {
        return [
            'amount' => $this->getAmount()->toFloat(),
            'currency' => $this->getCurrency()->getCurrencyCode(),
        ];
    }
}

As for test:

public function testJSONSerialize(): void
{
    $money = Money::of('5.50', 'USD');
    $got = $money->jsonSerialize();

    $expected = [
        'amount' => 5.50,
        'currency' => 'USD'
    ];

    $this->assertEquals($expected, $got);
}

Also it needed ext-json in composer

"require": {
    "ext-json": "*"
},
@gmhafiz
Copy link
Author

gmhafiz commented Sep 26, 2022

I realize there is a PR #52 which will allow ourselves to implement JsonSerializable interface.

Let me know if you want to have a built-in jsonSerialize() or just let the library user to implement this ourselves. If this ever gets implemented, need to let library users to know that it is a breaking change.

@BenMorel
Copy link
Member

BenMorel commented Oct 5, 2022

Hi, thanks for the feature request.

JsonSerializable support has been added in version 0.7.0!

@BenMorel BenMorel closed this as completed Oct 5, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants