需要JSON:
{
"catalog":
[
{
"city":{},
"hotels":
[
{}
]
}
]
}
班级:
@JsonSerialize(using = CustomSerializer.class)
private Set<Hotel> catalog= new TreeSet<>();
我的CustomSerializer:
@Override
public void serialize(Set<Hotel> hotels, JsonGenerator gen, SerializerProvider provider) throws IOException {
//sort and group
Map<City,List<Hotel>> hotelMap = hotels.stream()
.sorted(comparing(Hotel::getName, String.CASE_INSENSITIVE_ORDER))
.collect(groupingBy(Hotel::getCity));
// [
gen.writeStartArray();
hotelMap.entrySet().forEach(entry -> {
try {
// {
gen.writeStartObject();
// "city":{}
gen.writeObjectField("city", entry.getKey());
// "hotels":
gen.writeFieldName("hotels");
// [
gen.writeStartArray();
for (Hotel hotel: entry.getValue()
) {
// {}
gen.writeStartObject();
gen.writeObject(hotel);
gen.writeEndObject();
}
// ]
gen.writeEndArray();
// }
gen.writeEndObject();
} catch (IOException e) {
e.printStackTrace();
}
});
// ]
gen.writeEndArray();
}
序列化器将写入一个对象数组,该对象数组由城市和旅馆列表组成。我认为代码中的顺序正确,但是出现了错误"current context not an array but object"
。
问题出在哪里?