基于jackson 将一个String 类型的Json字符串对外输出成 json 格式。

  1. 注解
@Documented
@JacksonAnnotationsInside
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@JsonSerialize(using = StringToJsonSerializer.class)
public @interface JacksonStringToJson {
}

  1. 实现

@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;
        }
    }
}

  1. 示例
    image

  2. 效果
    image

posted @ 2022-06-29 18:39  空明师兄  阅读(511)  评论(0编辑  收藏  举报