How to do bool type checks on json using jmsserialize

How to force boolean type checks when json deserialization using jmsserializerbunlde? for example, how can I deny input, for example:

{"boolField": "false"}

from deserialization and cast to boolean true?

I am using jmsserializerbundle and the symfony2 validation library.

My model field annotations:

/** * @var bool * @Assert\NotNull() * @Assert\Type(type="bool") * @Type(name="boolean") * @SerializedName("boolField") */ private $boolField; 

I deserialize and then do the validation.

  $str = '{"boolField": "false"}'; $object = $serializer->deserialize($str, TestModel::class, 'json'); $validator->validate($object); print_r($object) TestModel Object ( [boolField:TestModel:private] => 1 ) 

This does not return errors, but has a side effect of my model, for which the value of $ boolField is set to true.

If I delete the @Type annotation, it will not be deserialized.

I can change the jmserialize type to a string and then the @PostDeserialize method to convert these strings to booleans, but is there a cleaner way?

+4
source share
1 answer

In your example:

 $str = '{"boolField": "false"}'; 

'boolField' is a string, not a boolean.

Can

 $str = '{"boolField": false}'; 

will work better.

(unverified)

0
source

All Articles