gpt4 book ai didi

php - 在 JMS 序列化程序中排除空属性

转载 作者:行者123 更新时间:2023-12-03 16:16:06 25 4
gpt4 key购买 nike

我使用的 XML API 可以选择仅检索响应的一部分。
这导致生成的对象有很多 NULL如果使用此功能,则属性。
有没有办法真正跳过NULL特性?我试图实现排除策略

shouldSkipProperty(PropertyMetadata $property, Context $context)`

但我意识到无法访问当前的属性值。

一个例子是以下类

class Hotel {
/**
* @Type("string")
*/
public $id;

/**
* @Type("integer")
*/
public $bookable;

/**
* @Type("string")
*/
public $name;

/**
* @Type("integer")
*/
public $type;

/**
* @Type("double")
*/
public $stars;

/**
* @Type("MssPhp\Schema\Response\Address")
*/
public $address;

/**
* @Type("integer")
*/
public $themes;

/**
* @Type("integer")
*/
public $features;

/**
* @Type("MssPhp\Schema\Response\Location")
*/
public $location;

/**
* @Type("MssPhp\Schema\Response\Pos")
*/
public $pos;

/**
* @Type("integer")
*/
public $price_engine;

/**
* @Type("string")
*/
public $language;

/**
* @Type("integer")
*/
public $price_from;
}

在此特定 api 调用中反序列化以下对象,其中包含大量 null特性。
"hotel": [
{
"id": "11230",
"bookable": 1,
"name": "Hotel Test",
"type": 1,
"stars": 3,
"address": null,
"themes": null,
"features": null,
"location": null,
"pos": null,
"price_engine": 0,
"language": "de",
"price_from": 56
}
]

但我希望它是
"hotel": [
{
"id": "11230",
"bookable": 1,
"name": "Hotel Test",
"type": 1,
"stars": 3,
"price_engine": 0,
"language": "de",
"price_from": 56
}
]

最佳答案

您可以配置 JMS Serializer 跳过 null像这样的属性:

$serializer = JMS\SerializerBuilder::create();              
$serializedString = $serializer->serialize(
$data,
'xml',
JMS\SerializationContext::create()->setSerializeNull(true)
);

取自 this issue .

更新:

不幸的是,如果您在反序列化时不想要空属性,那么除了自己删除它们之外别无他法。

但是,我不确定您实际想要删除这些属性的用例是什么,但它看起来不像 Hotel类包含很多逻辑。在这种情况下,我想知道结果是否应该是一个类?

我认为将数据表示为关联数组而不是对象会更自然。当然,JMS Serializer 无法将您的数据反序列化为数组,因此您将需要一个数据传输对象。

加上 dumpArray就够了和 loadArray您现有的方法 Hotel类(class)。这些将用于将数据转换为您想要的结果,反之亦然。有你的 DTO。
/**
* Sets the object's properties based on the passed array
*/
public function loadArray(array $data)
{
}

/**
* Returns an associative array based on the objects properties
*/
public function dumpArray()
{
// filter out the properties that are empty here
}

我相信这是最干净的方法,它可能反射(reflect)了你想要做的更多。

我希望这有帮助。

关于php - 在 JMS 序列化程序中排除空属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36429671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com