- 注解
@Documented
@JacksonAnnotationsInside
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@JsonSerialize(using = StringToJsonSerializer.class)
public @interface JacksonStringToJson {
}
- 实现
@JsonComponent
public class StringToJsonSerializer extends JsonSerializer<String> {
@Resource
private ObjectMapper objectMapper;
public StringToJsonSerializer() {
}
@Override
public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if (null == s) {
jsonGenerator.writeObject(null);
return;
}
try {
if (s.startsWith("[")) {
s = MessageFormat.format("'{' \"data\": {0} '}'", s);
jsonGenerator.writeObject(Objects.requireNonNull(str2Json(s, Map.class)).get("data"));
} else {
jsonGenerator.writeObject(str2Json(s, Map.class));
}
} catch (Exception ex) {
jsonGenerator.writeObject(null);
}
}
public <T> T str2Json(String json, Class<T> clazz) {
if (!StringUtils.hasText(json) || clazz == null) {
return null;
}
try {
return clazz.equals(String.class) ? (T) json : objectMapper.readValue(json, clazz);
} catch (Exception e) {
return null;
}
}
}
-
示例
-
效果