package com.tourguide.modules.review.util;
|
|
import com.fasterxml.jackson.databind.JsonNode;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import java.util.ArrayList;
|
import java.util.Collections;
|
import java.util.List;
|
|
/**
|
* 将评价图片字段兼容解析为图片地址列表。
|
* 新数据使用 JSON 数组,历史数据可能仍是 JSON 字符串或逗号分隔值。
|
*/
|
public final class ReviewImageParser {
|
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
private static final int MAX_IMAGE_COUNT = 3;
|
|
private ReviewImageParser() {
|
}
|
|
public static List<String> parse(String value) {
|
if (value == null || value.trim().isEmpty()) {
|
return Collections.emptyList();
|
}
|
|
try {
|
JsonNode node = OBJECT_MAPPER.readTree(value.trim());
|
if (node.isArray()) {
|
List<String> images = new ArrayList<String>();
|
for (JsonNode item : node) {
|
if (item.isTextual()) {
|
addImage(images, item.asText());
|
}
|
}
|
return images;
|
}
|
if (node.isTextual()) {
|
return parseDelimited(node.asText());
|
}
|
} catch (Exception ignored) {
|
// 兼容早期非 JSON 存储格式,继续按逗号分隔值解析。
|
}
|
return parseDelimited(value);
|
}
|
|
private static List<String> parseDelimited(String value) {
|
List<String> images = new ArrayList<String>();
|
for (String item : value.split(",")) {
|
addImage(images, item);
|
}
|
return images;
|
}
|
|
private static void addImage(List<String> images, String value) {
|
if (images.size() >= MAX_IMAGE_COUNT || value == null) {
|
return;
|
}
|
String image = value.trim();
|
if (!image.isEmpty() && !images.contains(image)) {
|
images.add(image);
|
}
|
}
|
}
|