|
|
@@ -0,0 +1,56 @@
|
|
|
+package shop.alien.entity.store.dto.deserializer;
|
|
|
+
|
|
|
+import com.fasterxml.jackson.core.JsonParser;
|
|
|
+import com.fasterxml.jackson.core.JsonProcessingException;
|
|
|
+import com.fasterxml.jackson.databind.DeserializationContext;
|
|
|
+import com.fasterxml.jackson.databind.JsonDeserializer;
|
|
|
+import com.fasterxml.jackson.databind.JsonNode;
|
|
|
+import com.fasterxml.jackson.databind.ObjectMapper;
|
|
|
+
|
|
|
+import java.io.IOException;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 自定义反序列化器:将字符串或JSON数组/对象转换为字符串
|
|
|
+ * 支持以下格式:
|
|
|
+ * - 字符串:"xxx" 或 "[{\"video\":\"...\",\"cover\":\"...\"}]"
|
|
|
+ * - JSON数组:[{"video":"...","cover":"..."}]
|
|
|
+ * - JSON对象:{"video":"...","cover":"..."}
|
|
|
+ * - null:返回null
|
|
|
+ *
|
|
|
+ * @author system
|
|
|
+ * @since 2025-01-16
|
|
|
+ */
|
|
|
+public class JsonStringDeserializer extends JsonDeserializer<String> {
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
|
|
|
+ JsonNode node = p.getCodec().readTree(p);
|
|
|
+
|
|
|
+ // 如果为null,返回null
|
|
|
+ if (node == null || node.isNull()) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 如果是字符串,直接返回
|
|
|
+ if (node.isTextual()) {
|
|
|
+ return node.asText();
|
|
|
+ }
|
|
|
+
|
|
|
+ // 如果是数组或对象,转换为JSON字符串
|
|
|
+ if (node.isArray() || node.isObject()) {
|
|
|
+ try {
|
|
|
+ // 使用ObjectMapper将JsonNode转换为JSON字符串
|
|
|
+ ObjectMapper mapper = (ObjectMapper) p.getCodec();
|
|
|
+ return mapper.writeValueAsString(node);
|
|
|
+ } catch (JsonProcessingException e) {
|
|
|
+ // 如果转换失败,使用toString()方法(注意:这可能不会生成标准的JSON格式)
|
|
|
+ // 但作为兜底方案,仍然返回
|
|
|
+ return node.toString();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // 其他类型(数字、布尔值等),转换为字符串
|
|
|
+ return node.asText();
|
|
|
+ }
|
|
|
+}
|
|
|
+
|