6

Symfony2 の PUT リクエストから JSON を使用する REST API を作成しようとしています。JSON をエンティティに逆シリアル化することはある程度機能しますが、JSON 内のプロパティの型がエンティティの対応するプロパティと一致しない場合、JMS シリアライザーは例外をスローするのではなく、JSON から型を強制するようです。

たとえば…</p>

{ "id" : "123" }

…結果は…</p>

int(123)

…プロパティidがエンティティで整数として定義されている場合。

しかし、代わりに JMS シリアライザーが例外をスローするようにしたいと考えています。これを達成する方法を知っている人はいますか?

2016-02-27 更新

私が見つけた JMS シリアライザーの型処理に関する 1 つの問題は次のとおりです。

{ "id" : "n123" }

結果は…</p>

int(0)

これはまったく望ましくありません。

誰かが私を正しい方向に向けることができますか?

4

2 に答える 2

6

Github でヘルプを取得した後、自分の質問に対する回答を共有したいと思います。

JMS\Serializer\Handler\SubscribingHandlerInterface解決策の鍵は、 (たとえば a )を実装するカスタム ハンドラを使用することStrictIntegerHandlerです。

<?php
namespace MyBundle\Serializer;

use JMS\Serializer\Context;
use JMS\Serializer\GraphNavigator;
use JMS\Serializer\Handler\SubscribingHandlerInterface;
use JMS\Serializer\JsonDeserializationVisitor;
use JMS\Serializer\JsonSerializationVisitor;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

class StrictIntegerHandler implements SubscribingHandlerInterface
{
    public static function getSubscribingMethods()
    {
        return [
            [
                'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
                'format' => 'json',
                'type' => 'strict_integer',
                'method' => 'deserializeStrictIntegerFromJSON',
            ],
            [
                'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
                'format' => 'json',
                'type' => 'strict_integer',
                'method' => 'serializeStrictIntegerToJSON',
            ],
        ];
    }

    public function deserializeStrictIntegerFromJSON(JsonDeserializationVisitor $visitor, $data, array $type)
    {
        return $data;
    }

    public function serializeStrictIntegerToJSON(JsonSerializationVisitor $visitor, $data, array $type, Context $context)
    {
        return $visitor->visitInteger($data, $type, $context);
    }
}

次に、シリアライザーをサービスとして定義する必要があります。

services:
    mybundle.serializer.strictinteger:
        class: MyBundle\Serializer\StrictIntegerHandler
        tags:
            - { name: jms_serializer.subscribing_handler }

次に、タイプを使用できるようになりますstrict_integer

MyBundle\Entity\MyEntity:
    exclusion_policy: ALL
    properties:
        id:
            expose: true
            type: strict_integer

その後、コントローラーでのデシリアライズは通常どおりに機能します。

おまけ: 型バリデーターの使用がようやく意味をなすようになりました:

MyBundle\Entity\MyEntity:
    properties:
        id:
            - Type:
                type: integer
                message: id {{ value }} is not an integer.

これが同じ問題を抱えている人に役立つことを願っています。

于 2016-04-20T12:58:05.577 に答える