记一次springboot jackson序列化问题---

343 阅读1分钟
com.fasterxml.jackson.databind.JsonMappingException:Can not write a field name, expecting a value

项目bean中使用了自定义的序列化注解,输入为空的情况下不会写入到josn生成器中。伪代码如下

public static class CustomSerializer extends JsonSerializer<List<String>>{

    @Override
    public void serialize(List<String> strings, JsonGenerator jg, SerializerProvider sp) throws IOException {
        if (CollectionUtils.isNotEmpty(strings)) {
            jg.writeArray(new String[]{"1"},0,1);
        }
    }
}

出现上述报错,正确写法应该无论输入为何,都应将返回值写入对象中

public static class CustomSerializer extends JsonSerializer<List<String>>{

    @Override
    public void serialize(List<String> strings, JsonGenerator jg, SerializerProvider sp) throws IOException {
        if (CollectionUtils.isNotEmpty(strings)) {
            jg.writeArray(new String[]{"1"},0,1);
        }else {
            jg.writeArray(new String[]{},0,0);
        }
    }
}

问题解决