schmittjoh / jmsserializerbundle Goto Github PK
View Code? Open in Web Editor NEWEasily serialize, and deserialize data of any complexity (supports XML, JSON, YAML)
Home Page: http://jmsyst.com/bundles/JMSSerializerBundle
License: MIT License
Easily serialize, and deserialize data of any complexity (supports XML, JSON, YAML)
Home Page: http://jmsyst.com/bundles/JMSSerializerBundle
License: MIT License
Since commit e2a6adb there has been a notice generated, which causes PHPUnit to fail with error exceptions on. When I revert to the previous commit, everything passes fine.
The class/object being serialized doesn't have anything special to it, just standard strings and ints for properties and standard getters/setters. I'm serializing it to XML.
Actual exception from PHPUnit -
ErrorException: Notice: Undefined offset: 13 in .../bundles/JMS/SerializerBundle/Metadata/PropertyMetadata.php line 107
Let me know if you want any more information that I can provide. When I have time, I'll try and post a simple example script that reproduces the error.
When I try do something in console I get:
[ErrorException]
Warning: date_default_timezone_get(): It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Europe/Berlin' for 'CEST/2.0/DST' instead in /path/vendor/bundles/JMS/SerializerBundle/DependencyInjection/Configuration.php line 56
Mac OS X Lion / PHP 5.3.2
I've created an entity that uses __get() and __set() for access while still keeping properties protected for Doctrine. I've also implemented __call() to allow for more traditional-looking getters and setters, but JMSSerializerBundle can only use reflection (which bypasses my __get() implementation) or existing public methods. If there were another AccessType like "magic_call" it would be compatible with PHP's magic methods. For the moment I've overwritten the setAccessor() method on PropertyMetadata to avoid the checks for method existence, but that's obviously not right.
If anyone's wondering why I still want my __get() call to fire when serialization occurs, I've created the ability to have an "optional" getter in case I need to modify the data on the way out, and I'd like JMSSerializerBundle to respect that. Something like this:
public function __get($property) {
$getter = '_get' . ucfirst($property);
if (method_exists($this, $getter)) {
return $this->$getter();
}
if (property_exists($this, $property) && in_array($property, $this->accessible) ) {
return $this->$property;
}
}
Need same as #46 for mongodb-odm
.
Can start implement this, only in a week by @yethee example.
Hooks question:
for now my @PreSerialize
does not called, because of I pass to serializer proxy but pass real object.
Definitely it`s because of proxy class have not hook method, and annotation above it.
Will this fix if I implement @yethee approach from #46 ?
PS still use separate serializer map for each proxy with one line exclusion_policy: ALL
Example of desired output:
Granted that $game
is an object.
$data = array(
'game' => $game,
'players' => array(
'Alice',
'Bob',
),
);
<results>
<game>
<id>3</id>
<name>Foo</name>
</game>
<players>
<entry>Alice</entry>
<entry>Bob</entry>
</players>
</results>
To name xml elements, distinction between lists (players) and maps (the top-level array) could be done by using isset($array[0])
, or alternatively ìs_numeric($key)
on every key to know if it should be called $key
or entry
.
[Symfony\Component\Config\Definition\Exception\InvalidDefinitionException]
Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition::defaultValue() is not applicable to concrete nodes.
I know it's related with latest symfony 2.1-dev changes. Any quick solution?
still adjusting to how JMSSerialierBundle works, but I wonder if it would make sense to support the NormalizeableInterface in cases where its simply not feasible to use annotations, but where one doesnt want to register a filter (for whatever reason). also it would make it easier for people to migrate from the core Serializer to JMSSerializerBundle.
I think the current serialization groups are a bit weird because they don't work like the validator component, so first of all it's confusing because it's not familiar, and second I think the behavior of the validator makes more sense (that may be bias from the former though).
Example: I define group User and group Item and attach them like this:
Item {
name // no group
owner // group "Item"
}
User {
name // no group
items // group "User"
}
If you agree I can work on a PR.
I recently notice that object serialization stopped working in a project. I can't seem to nail down the problem. It seems to work in my test environment but not in dev/prod environment.
I am using the latest master and metadata 1.1.1
and have cleared the cache.
Here is my stack trace:
<error code="500" message="Internal Server Error">
<exception class="ErrorException" message="Notice: Undefined index: product in C:\wamp\www\tardis\vendor\doctrine\lib\Doctrine\ORM\Persisters\BasicEntityPersister.php line 1280">
<traces>
<trace>
at n/a in C:\wamp\www\tardis\vendor\symfony\src\Symfony\Component\HttpKernel\Debug\ErrorHandler.php line 65
</trace>
<trace>
at Symfony\Component\HttpKernel\Debug\ErrorHandler->handle('8', 'Undefined index: product', 'C:\wamp\www\tardis\vendor\doctrine\lib\Doctrine\ORM\Persisters\BasicEntityPersister.php', '1280', array('assoc' => array('fieldName' => 'parts', 'mappedBy' => 'product', 'targetEntity' => 'Hammond\PartBundle\Entity\Part', 'cascade' => array(), 'orphanRemoval' => false, 'fetch' => '2', 'orderBy' => array('number' => 'ASC'), 'type' => '4', 'inversedBy' => null, 'isOwningSide' => false, 'sourceEntity' => 'Hammond\ProductBundle\Entity\Product', 'isCascadeRemove' => false, 'isCascadePersist' => false, 'isCascadeRefresh' => false, 'isCascadeMerge' => false, 'isCascadeDetach' => false), 'sourceEntity' => object(Hammond\ProductBundle\Entity\Product), 'offset' => null, 'limit' => null, 'criteria' => array())) in C:\wamp\www\tardis\vendor\doctrine\lib\Doctrine\ORM\Persisters\BasicEntityPersister.php line 1280
</trace>
<trace>
at Doctrine\ORM\Persisters\BasicEntityPersister->getOneToManyStatement(array('fieldName' => 'parts', 'mappedBy' => 'product', 'targetEntity' => 'Hammond\PartBundle\Entity\Part', 'cascade' => array(), 'orphanRemoval' => false, 'fetch' => '2', 'orderBy' => array('number' => 'ASC'), 'type' => '4', 'inversedBy' => null, 'isOwningSide' => false, 'sourceEntity' => 'Hammond\ProductBundle\Entity\Product', 'isCascadeRemove' => false, 'isCascadePersist' => false, 'isCascadeRefresh' => false, 'isCascadeMerge' => false, 'isCascadeDetach' => false), object(Hammond\ProductBundle\Entity\Product)) in C:\wamp\www\tardis\vendor\doctrine\lib\Doctrine\ORM\Persisters\BasicEntityPersister.php line 1264
</trace>
<trace>
at Doctrine\ORM\Persisters\BasicEntityPersister->loadOneToManyCollection(array('fieldName' => 'parts', 'mappedBy' => 'product', 'targetEntity' => 'Hammond\PartBundle\Entity\Part', 'cascade' => array(), 'orphanRemoval' => false, 'fetch' => '2', 'orderBy' => array('number' => 'ASC'), 'type' => '4', 'inversedBy' => null, 'isOwningSide' => false, 'sourceEntity' => 'Hammond\ProductBundle\Entity\Product', 'isCascadeRemove' => false, 'isCascadePersist' => false, 'isCascadeRefresh' => false, 'isCascadeMerge' => false, 'isCascadeDetach' => false), object(Hammond\ProductBundle\Entity\Product), object(Doctrine\ORM\PersistentCollection)) in C:\wamp\www\tardis\vendor\doctrine\lib\Doctrine\ORM\UnitOfWork.php line 2160
</trace>
<trace>
at Doctrine\ORM\UnitOfWork->loadCollection(object(Doctrine\ORM\PersistentCollection)) in C:\wamp\www\tardis\vendor\doctrine\lib\Doctrine\ORM\PersistentCollection.php line 207
</trace>
<trace>
at Doctrine\ORM\PersistentCollection->initialize() in C:\wamp\www\tardis\vendor\doctrine\lib\Doctrine\ORM\PersistentCollection.php line 512
</trace>
<trace>
at Doctrine\ORM\PersistentCollection->getIterator() in C:\wamp\www\tardis\vendor\bundles\JMS\SerializerBundle\Serializer\XmlSerializationVisitor.php line 116
</trace>
<trace>
at JMS\SerializerBundle\Serializer\XmlSerializationVisitor->visitArray(object(Doctrine\ORM\PersistentCollection), 'Doctrine\ORM\PersistentCollection') in C:\wamp\www\tardis\vendor\bundles\JMS\SerializerBundle\Serializer\XmlSerializationVisitor.php line 135
</trace>
<trace>
at JMS\SerializerBundle\Serializer\XmlSerializationVisitor->visitTraversable(object(Doctrine\ORM\PersistentCollection), 'Doctrine\ORM\PersistentCollection') in C:\wamp\www\tardis\vendor\bundles\JMS\SerializerBundle\Serializer\GraphNavigator.php line 105
</trace>
<trace>
at JMS\SerializerBundle\Serializer\GraphNavigator->accept(object(Doctrine\ORM\PersistentCollection), null, object(JMS\SerializerBundle\Serializer\XmlSerializationVisitor)) in C:\wamp\www\tardis\vendor\bundles\JMS\SerializerBundle\Serializer\XmlSerializationVisitor.php line 193
</trace>
<trace>
at JMS\SerializerBundle\Serializer\XmlSerializationVisitor->visitProperty(object(JMS\SerializerBundle\Metadata\PropertyMetadata), object(Hammond\ProductBundle\Entity\Product)) in C:\wamp\www\tardis\vendor\bundles\JMS\SerializerBundle\Serializer\GraphNavigator.php line 123
</trace>
<trace>
at JMS\SerializerBundle\Serializer\GraphNavigator->accept(object(Hammond\ProductBundle\Entity\Product), null, object(JMS\SerializerBundle\Serializer\XmlSerializationVisitor)) in C:\wamp\www\tardis\vendor\bundles\JMS\SerializerBundle\Serializer\XmlSerializationVisitor.php line 193
</trace>
<trace>
at JMS\SerializerBundle\Serializer\XmlSerializationVisitor->visitProperty(object(JMS\SerializerBundle\Metadata\PropertyMetadata), object(Hammond\ProductBundle\Entity\Accessory)) in C:\wamp\www\tardis\vendor\bundles\JMS\SerializerBundle\Serializer\GraphNavigator.php line 123
</trace>
<trace>
at JMS\SerializerBundle\Serializer\GraphNavigator->accept(object(Hammond\ProductBundle\Entity\Accessory), null, object(JMS\SerializerBundle\Serializer\XmlSerializationVisitor)) in C:\wamp\www\tardis\vendor\bundles\JMS\SerializerBundle\Serializer\XmlSerializationVisitor.php line 125
</trace>
<trace>
at JMS\SerializerBundle\Serializer\XmlSerializationVisitor->visitArray(object(Doctrine\ORM\PersistentCollection), 'Doctrine\ORM\PersistentCollection') in C:\wamp\www\tardis\vendor\bundles\JMS\SerializerBundle\Serializer\XmlSerializationVisitor.php line 135
</trace>
<trace>
at JMS\SerializerBundle\Serializer\XmlSerializationVisitor->visitTraversable(object(Doctrine\ORM\PersistentCollection), 'Doctrine\ORM\PersistentCollection') in C:\wamp\www\tardis\vendor\bundles\JMS\SerializerBundle\Serializer\GraphNavigator.php line 105
</trace>
<trace>
at JMS\SerializerBundle\Serializer\GraphNavigator->accept(object(Doctrine\ORM\PersistentCollection), null, object(JMS\SerializerBundle\Serializer\XmlSerializationVisitor)) in C:\wamp\www\tardis\vendor\bundles\JMS\SerializerBundle\Serializer\XmlSerializationVisitor.php line 193
</trace>
<trace>
at JMS\SerializerBundle\Serializer\XmlSerializationVisitor->visitProperty(object(JMS\SerializerBundle\Metadata\PropertyMetadata), object(Hammond\ProductBundle\Entity\Enclosure)) in C:\wamp\www\tardis\vendor\bundles\JMS\SerializerBundle\Serializer\GraphNavigator.php line 123
</trace>
<trace>
at JMS\SerializerBundle\Serializer\GraphNavigator->accept(object(Hammond\ProductBundle\Entity\Enclosure), null, object(JMS\SerializerBundle\Serializer\XmlSerializationVisitor)) in C:\wamp\www\tardis\vendor\bundles\JMS\SerializerBundle\Serializer\Serializer.php line 61
</trace>
<trace>
at JMS\SerializerBundle\Serializer\Serializer->serialize(object(Hammond\ProductBundle\Entity\Enclosure), 'xml') in C:\wamp\www\tardis\src\Hammond\CoreBundle\Controller\PageController.php line 43
</trace>
...
We are porting a current API from using the core NormalizeableInterface to SerializationHandlerInterface.
Currently for JSON we end up with something like:
http://screencast.com/t/5j8IiEXGmjsS
And for XML something like:
http://screencast.com/t/j0KRbKTnIJ63
With the following code we managed to handle JSON, but for XML we seem to have to set the entry name somehow. So we looked into setting this, but found that we have to do that on a property metadata instance, but we are not sure what property, since we have an array of objects.
public function serialize(VisitorInterface $visitor, $data, $type, &$visited)
{
$visited = true;
if ($visitor instanceof JsonSerializationVisitor) {
return $this->toArray();
}
if ($visitor instanceof XmlSerializationVisitor) {
//$md = new PropertyMetadata();
//$md->xmlEntryName = 'article';
//$visitor->setCurrentMetadata($md);
$visitor->visitArray($this->toArray(), $type);
return;
}
}
Dear all, I'm new to JMS, got a question that I need some help on.
Suppose I have a model that has fields A and B. So serializing that gives only id, A and B, what if I want to expose as a JSON a field C (which is NOT attribute) and is a function of A and B?
e.g.
{"A":2, "B":4, "C":16}
, where C is A^B.
Something like that.
Thanks!!!
In https://github.com/schmittjoh/JMSSerializerBundle/blob/master/Resources/doc/index.rst when talking about how to upgrade metadata to 1.1.0 you might also want to mention that you need to remove (or replace) the entry from deps.lock, otherwise php bin/vendors install
will not do anything.
think we talked about this on IRC before and IIRC we didn't really have a concept for a solution just yet ..
Hi guys!
I was wondering if there was a specific reason for not having a naming strategy that simply uses the property name as the end field name. The use case is serializing an object for consumption by a BackboneJS model, but then a server-side Sf2 form to handle the BackboneJS model save (e.g. deserialize the posted data then proxy through a form).
Unless anyone can see a reason against this, I'm happy to make a PR for this.
Thanks!
If I have a ConstraintViolationList instance if there some way to still be able to use a custom normalizer? The issue is that ConstraintViolationList implements \Traversable, which triggers the native php normalizer. Furthermore the class is defined by a 3rd party meaning there is no way to add annotations to it directly (or easily).
Hi I was trying to have a go with this bundle but I'm getting
Fatal error: Class 'Metadata\Driver\LazyLoadingDriver' not found
I'm using
Symfony 2.0.7
metadata v1.1.0
all namespaces have been added to autoload.php
I can't see where the problem is. Any idea?
Thanks in advance.
I am using the FOSUserBundle and have my own entity extended of the FOSUserBundle Model.
In my user entity I want to serialize some things. But the rest should be excluded.
So I added @Serializer\ExclusionPolicy("all")
but somehow all the UserBundle's properties are exposed.
In my cache directory I keep getting this file: serializer/FOS-UserBundle-Model-User.cache.php
.
How can I get rid of this?
In #9 it was suggested to use the @Type
annotation with an additional attribute for this:
#56 (comment)
When serializing an associated array to xml, the keys are lost, it is currently not the case with Json or Yaml serialization.
Let's say we have the following array:
$associatedArray = array(
array(
'foo' => 'bar',
'boo' => 'far',
'faz',
)
);
YAML serialization results in:
foo: bar
boo: far
0: faz
JSON serialization results in:
{
"foo":"bar",
"boo":"far",
"0":"faz"
}
However, XML serialization results in:
<entry><![CDATA[bar]]></entry>
<entry><![CDATA[far]]></entry>
<entry><![CDATA[faz]]></entry>
When the excepted result would be:
<foo><![CDATA[bar]]></foo>
<boo><![CDATA[far]]></boo>
<entry><![CDATA[faz]]></entry>
PropertyMetadata and it's parameters seems to be hardcoded into all the metadata drivers, which seems to make it impossible to add additional metadata.
Ideally you should be able to add any custom metadata you want and the visitors would just ignore it since they don't understand, however this additional data would then be available to custom handlers.
Here is an example of a simple controller that can cause a validation error:
https://github.com/liip/HelloBundle/blob/master/Controller/HelloController.php#L69
In the case of a validation error a ConstraintViolationList
instance is passed to the view layer which then needs to be normalized using the ValidatorConstraintViolationListNormalizer
. However since ConstraintViolationList
is 3rd party code I cannot add the annotations.
What do you propose here? Wrap the ConstraintViolationList
into an annotated class?
Note in the FOSRestBundle I handle registering normalizers via the config for specific classes and for the above case I register a normalizer by default:
https://github.com/FriendsOfSymfony/RestBundle/blob/master/DependencyInjection/FOSRestExtension.php#L42
Also the FOSUserBundle Serializer has support for a fallback normalizer, I guess this is really what I would want to use here. Aka I would want to register the AnnotatedNormalizer
as a fallback normalizer, but for this configureSerializer() doesnt really work well. What I would rather want is for the SerializerBundle to offer an AnnotatedNormalizer
service I could reference that is setup with the naming/exclusion strategy the user has configured.
I have some collections which are by default using some non numerical key, but when serializing I want to always use numeric keys for these collections. Right now I need to handle this via a @PreSerialize method.
PHP 5.4.0 includes support for Traits and with them, new patterns for "drop in" functionality will likely gain attraction in the following months.
For example, a User
could use Traits for mapping social networks profiles, such as Facebook or Twitter. Another interesting use case is to easily include Doctrine behaviors without having to rely on much more complex code. KnpLabs recently blogged about this new way of dealing with behaviors on a blog post.
This issue is a request to include support for mapping metadata when using Traits.
The annotation "@Proxy" in method Doctrine\MongoDB\Connection::close() was never imported
I use Doctrine ODM for my application. There is not Doctrine ODM proxies handler for now, but I have created issue #50.
@stof here #34 you advised use doctrine-common 2.1.x
I am using latest doctrine-common, but still have issue.
I am on this commit now doctrine/common@9ad3d51
To temporary fix this I have created separate serializer map for each proxy with one line exclusion_policy: ALL
SetCustomHandlersPass class has a typo in tag name ("jms_serializer.deserialization_handlers" instead of "jms_serializer.deserialization_handler"). Custom handlers are not set because of this.
So for example property of type "DateTime" is not deserialized properly and has empty value.
I like the approach with tagging, but the order in which normalizers are registered is very important, so I guess there needs to be a tag parameter to set the order. What do you think?
When I set the annotation @Accessor(getter="foo")
on a property I expect this property to be read-only.
Example:
<?php
class ObjectType
{
/**
* @Serializer\Type("integer")
* @Serializer\Accessor(getter="getId")
*/
protected $id;
}
$types = $serializer->deserialize(
'[{"id":123123,"bundle":"TestBundle","controller":"TestController"}]',
'array<ObjectType>',
'json'
);
Result:
object(ObjectType)[58]
protected 'id' => int 123123
protected 'name' => null
protected 'bundle' => string 'TestBundle' (length=10)
protected 'controller' => string 'TestController' (length=14)
I could skip some validation/cleaning logic if id
is never set by deserialize
.
right now f.e the version and groups exclusion strategies cannot be used together
The readme says to make sure your version of 'metadata' is 1.1.0, but to do this you need to take out the line relating to metadata in
deps.lock
as well as the step that's mentioned. You get some message about Lazyloader otherwise.
Hey guys,
I think I've setup the bundle correctly using the instructions in the FOS Rest bundle documentation. However when viewing either .xml or .json I get the following error:
[Semantical Error] The annotation "@OverRide" in method Doctrine\ORM\Mapping\ClassMetadataInfo::_validateAndCompleteOneToOneMapping() was never imported.
I'm using Symfony2 Standard with the master branch of the metadata bundle.
Here's my full config.yml, stacktrace and deps files: https://gist.github.com/1240315
Any help would be appreciated.
Cheers Leevi
I keep getting this error Undefined offset: 14 in vendor/bundles/JMS/SerializerBundle/Metadata/PropertyMetadata.php line 110 I have tried removing numerous fields from my model but no luck. Here is what I am trying to serialize.
(
[id:protected] => 4f6b899196acb81b17000006
[name:protected] => Test File
[url:protected] =>
[owner:protected] => BIMFS
[prefix:protected] => None
[dead_date:protected] =>
[created:protected] => 2012-03-22T15:20:33-05:00
)
/**
@xmlRoot("package")
@mongodb\Document
*/
class FileRecord
{
/**
Thanks,
CG
Hello,
i'm not sure if this is the correct place to comment this issue. I will try to explain the problem:
I've a User class with followers and people to follow throught another class (Follow entity). In follow entity there're of courser references to User entity... There're more entites related like Follow entity in my model... so... when i try to serialize it I get an error (function nesting level...) due (i supose) to the circular references.
I see in documentation that this bundle can handle with circular references of objects so I supose that I have some problem. Here is the example in pseudoPHP on my controller:
$user = entitityRepository->find(1);
$serializer = $this->get('serializer');
$json = $serializer->serialize($user, 'json');
...error... :(
to make it possible to dynamically configure the depth of the serialization of a given object graph
Hi,
I put into the deserializer a string (json_encoded) of a boolean field, it looks like : {"field":false}
As handler I use an object with a boolean field property.
When I submit strings {"field":true} or {"field":"foo"} my object field is set to true but it doesn't seems to work with false, neither with {"field":false} nor {"field":0}, the field is not set.
Any idea will be welcome :)
Btw gz for your work.
Hi. I'm having trouble when trying to serialize an object that has a reference to a Doctrine2 proxy class. If the proxy is initialized everything runs smoothly. Otherwise, I'm getting this error:
"ErrorException: Warning: SplObjectStorage::contains() expects parameter 1 to be object, resource given in D:\wamp\www\sgla\vendor\bundles\JMS\SerializerBundle\Serializer\GraphNavigator.php line 64 (uncaught exception) at D:\wamp\www\sgla\vendor\symfony\src\Symfony\Component\HttpKernel\Debug\ErrorHandler.php line 65"]|
Is this normal a normal behavior? Must I load the proxy before serializing in some way?
I have checked and nor __load neither __sleep methods are called in proxy class.
Thanks in advance
Hi,
I'm trying to define custom directory for serializer metadata, but I'm not able to define a resource for "path" key.
Using resource identifier as documented file locator is unable to convert it to a valid path.
This configuration wont work:
directories:
any-name:
namespace_prefix: My\FooBundle
path: @MyFooBundle/Resources/config/serializer
And this will:
directories:
any-name:
namespace_prefix: My\FooBundle
path: %kernel.root_dir%/../src/My/FooBundle/Resources/config/serializer
I think that Metadata\Driver\FileLocator is not able to convert @MyFooBundle/Resources/config/serializer in src/My/FooBundle/Resources/config/serializer.
Maybe the bundle should use Symfony\Component\HttpKernel\Config\FileLocator ?
Is simply a documentation error ?
It doesn't seem correct for a getter to change state like this. Is this a convention for serializer handlers?
Don't you think it'll be good to have PHP-serialization strategy?
It seems really easy to implement it (just like JsonSerializationVisitor with php_export() instead of json_encode()) and i think it will be useful not only for me.
If you think it'll be usefull I can implement it. (And also it'll be great to refactor hardcoded serialiation formats in DependencyInjection\JMSSerializerExtension:90)
Hi,
I've created a very basic Img class that I want to serialize/unserialize. I've defined a "type" property which could only be "main" or not be present at all.
This property is defined as this :
/**
* @Type("string")
* @XmlAttribute
* @SerializedName("type")
* @Since("1")
*/
protected $type = null;
My Class declaration is also really simple :
/**
* @AccessType("public_method")
* @XmlRoot("img")
*/
class Img {
And finally my setter method for the type property :
public function setType($type) {
$type = ($type === self::TYPE_MAIN) ? self::TYPE_MAIN : null;
$this->type = $type;
}
When I try to unserialize a simple version of an "img" node with an invalid value for "type", the setter method should be called and $type should be replaced by "null".
Problem : it's not. I've added some debug trace in my setter method and the unserializer does not use it even I've specified an AccessType to "public_method".
You can find code example on pastebin :
Adds about ~300ms overhead to initialization by just enabling this bundle.
Is there a way that you can override or define metadata only for the last class in hierarchy and that would be the rules you'd want the specific object to be serialized by.
The excellent example of where this would come in handy is when you are extending a user model from FOSUB and would like to exclude some properties from being serialized. The bundle doesn't ship with any serialization metadata and even if it would each user could have different expectations of what should and should not be serialized.
This would require some sort of merging all metadata in proper hierarchy.
I want to embed my serialized object into an array that I want to encode to json. But that doesn't seem to work as the serializer json_encodes the object.
$serialized = $this->get('serializer')->serialize(new MyObject(), 'json');
echo json_encode(array(
'success' => true,
'result' => $serialized
));
I could json_decode
my $serialized
but that seems really ugly.
How should I fix this? Should there be an option on the serialize
function to just return the $visitor
instead of $visitor->getResult()
? Or should I make my own handler?
Hi,
I would like to to deserialize this :
<offer>
<cost currency="USD">0.00</shippingCost>
</offer>
Into these classes :
class Offer{
/**
* @Type("Price")
*/
private $cost;
}
class Price {
/**
* @XmlAttribute
*/
private $currency;
/**
* @Type("double")
*/
private $price;
}
As you can see there is not attribute to tell that price
should be the content of the xml node. So it would be very useful to have some kind of @XmlContent
annotation to do this.
I'm using the agnostic storage pattern for a bundle and I have three User classes:
Vendor\Bundle\AuthenticationBundle\Model\User
|- Vendor\Bundle\AuthenticationBundle\Entity\User
|- Project\AuthenticationBundle\Entity\User
When using the @ExclusionPolicy("all")
on the Project\AuthenticationBundle\Entity\User
one would expect all properties of the parents to be also excluded. However, this is not the case and requires me to add the same exclusion policy on each parent, otherwise all the parent properties are serialized. This is a problem because I don't want to create a dependency like this for the bundles.
The problem seems to lie in the way AnnotationDriver
lists the class properties, since it doesn't take into account the parent class annotations, if set.
Is there a workaround for this?
Funny.
My deps looks like this:
[metadata]
git=http://github.com/schmittjoh/metadata.git
version=1.1.0
But each time I do
php bin/vendors install
I get:
Installing/Updating metadata
HEAD is now at 8717ad2 release 1.0.0
And I am getting this error trying to use serialiazer bundle:
Fatal error: Class 'Metadata\Driver\LazyLoadingDriver' not found
Please confirm if this is a bug or some misconception from my part.
As pointed out in #54 (comment) - having the possibility to define groups in Exclude and Expose much like validation groups work in Sf2 would be good:
@Expose(groups={"user"})
means that the property would only be exposed if the group user
is enabled. The serializer should allow multiple groups to be used at the same time. By default everything uses, and falls into, the "Default" group.
Hi. I'm currently using Dojo for client side development, and it allows the use of JSON referencing between objects, in a REST context. It'd be great if the bundle allowed this behaviour, since it would simplify the treatment of objects (for example: no need to load a doctrine2 proxy class before serializing and less processing).
More info about JSON referencing: http://www.sitepen.com/blog/2008/06/17/json-referencing-in-dojo/
Possible example:
Object A properties: id and a reference to Object B
Object B properties: id and name
With normal serializing:
Serializing of object A: { id: 1, objectB: { id: 2, name: "myName" } }
Using JSON reference serializing:
Serializing of object A: { id: 1, objectB: { $ref: "/object_b/2" } }
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.