如何為基礎型別(如字串或陣列)創建一個自定義的JMSSerializen處理程式?我們的目標是以非默認的方式(反)序列化某些屬性。例如,指定一個陣列屬性應被反序列化為CSV字串,而不是默認的JSON陣列,或者一個字串屬性應被反序列化為加密/編碼字串,等等。
雖然為自定義類創建這樣的處理程式沒有問題,但我卻很難為基本型別做同樣的事情。
class SyncableEntityHandler implements SubscribingHandlerInterface{
public static function getSubscribingMethods() {
return [
[
'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
'format' => 'json'。
'type' => 'SomeClass'。
'method' => 'serializeSomeClassToJson',
],
[
'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
'format' => 'json'。
'type' => 'SomeClass'。
'method' => 'deserializeSomeClassFromJson',
],
];
}
title">serializeSomeClassToJson(JsonSerializationVisitor $visitor, AbstractSyncableEntity $entity, array $type, Context $context) {
...
}
public function deserializeSome. title">deserializeSomeClassFromJson(JsonDeserializationVisitor $visitor, $entityGuid, array $type, Context $context) {
...
}
}
class OtherClass{
/*
* @JMSType("SomeClass")
*/
protected $someProperty;
/*
* @JMSType("array")
*/
protected $serializeToDefaultArray;
/*
* @JMSType("csv_array") // How to do this?
*/
protected $serializeToCSVString;
}
雖然我可以用'type' => 'array'創建一個處理程式來改變所有陣列的(去)序列化,但我不知道如何只選擇某些陣列。
我已經想過使用getters和setters來代替(例如,getPropertyAsCsvString()和setPropertyFromCsvString())。雖然這對自定義類是有效的,但我也想序列化一些第三方類,在這些類中,我不是用注解而是在.yaml檔案中指定序列化選項。給這些類添加getter和setters是不可能的(很容易)。此外,創建這些獲取器和設定器將增加大量的開銷。
那么,是否有辦法為某些屬性創建并指定特殊的處理程式?
uj5u.com熱心網友回復:
實作起來很簡單:
class CsvArrayHandler implements SubscribingHandlerInterface{
public static function getSubscribingMethods() {
return [
[
'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
'format' => 'json'。
'type' => 'csv_array',
'method' => 'serializeToJson',
],
[
'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
'format' => 'json'。
'type' => 'csv_array',
'method' => 'deserializeFromJson',
],
];
}
public function serializeSome? title">serializeSomeClassToJson(JsonSerializationVisitor $visitor, array $array, array $type, Context $context) {
return implode(', ', $array);
}
public function deserializeSome? title">deserializeSomeClassFromJson(JsonDeserializationVisitor $visitor, string $csvString, array $type, Context $context) {
return explode(',', $csvString) 。
}
}
然后只需用@JMSType("csv_array")來注釋你的屬性,并注冊處理程式。
注意,使用explode和implode不會轉義輸入,所以你可能想使用類似league/csv的東西代替。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/328347.html
標籤:
上一篇:PySpark和Kafka:org.apache.spark.SparkException。獲取JAR中的主類失敗,錯誤為'檔案檔案...不存在'。
