我有一个控制器,它以ResponseEntity
的形式返回对象列表,所返回的JSON
具有以下格式:
[
{
“name”:”a”,
“classes”:
[
“1”,”2”,”3”
]
}]
我想以以下格式对其进行重组:
[{“a”:[“1”,”2”,”3”]}]
我有一种预感,我必须制作自己的JSON Object
并以某些带有@JsonValue
注释的方法将其返回,但我不想这样做。
还有其他方法吗?
答案 0 :(得分:0)
您有两个选择:
package.json
-s的列表。在这种情况下,自定义序列化器应该很简单:
Map
简单用法:
class PojoSerializer extends JsonSerializer<Pojo> {
@Override
public void serialize(Pojo value, JsonGenerator gen, SerializerProvider provider) throws IOException {
gen.writeStartObject();
gen.writeObjectField(value.getName(), value.getClasses());
gen.writeEndObject();
}
}
打印:
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class JsonApp {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writeValue(System.out, Arrays.asList(new Pojo(), new Pojo()));
}
}
@JsonSerialize(using = PojoSerializer.class)
class Pojo {
private String name = "a";
private List<String> classes = Arrays.asList("1", "2", "3");
// getters, setters
}