Tôi đã có cùng một vấn đề ngày hôm nay và không bỏ cuộc cho đến khi tôi tìm thấy một giải pháp phù hợp thực sự tốt. Tôi không thể cập nhật thư viện áo từ 1.1.5 nó là một Legacy System. My Rest Service trả về một Danh sách và họ phải tuân theo các quy tắc đó.
- Lists rỗng được trả lại như [] (hầu như không thể) Lists
- Một phần tử được trả lại như [] (khó khăn nhưng chỉ cấu hình bản đồ)
- Nhiều Lists phần tử được trả lại như [] (dễ)
Bắt đầu từ dễ đến không thể.
3) không có gì hiện nay bình thường JSON Mapping
2) Đăng ký JAXBContextResolver như
@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {
private final JAXBContext context;
private final Set<Class<?>> types;
private Class<?>[] ctypes = { Pojo.class }; //your pojo class
public JAXBContextResolver() throws Exception {
this.types = new HashSet<Class<?>>(Arrays.asList(ctypes));
this.context = new JSONJAXBContext(JSONConfiguration.mapped()
.rootUnwrapping(true)
.arrays("propertyName") //that should rendered as JSONArray even if the List only contain one element but doesn't handle the empty Collection case
.build()
, ctypes);
}
@Override
public JAXBContext getContext(Class<?> objectType) {
return (types.contains(objectType)) ? context : null;
}
}
1) Các phương pháp sau đây sau đây chỉ hoạt động cho lớp Collections $ EmptyList. Bạn có thể tìm cách làm cho nó chung cho tất cả các Bộ sưu tập chúng trống không. Có thể mã đối phó với EmptyList như vậy.
@Provider
@Produces(value={MediaType.APPLICATION_JSON})
public class EmptyListWriter implements MessageBodyWriter<AbstractList> {
private static final String EMPTY_JSON_ARRAY = "[]";
@Override
public long getSize(AbstractList list, Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType) {
return EMPTY_JSON_ARRAY.length();
}
@Override
public boolean isWriteable(Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType) {
return clazz.getName().equals("java.util.Collections$EmptyList");
}
@Override
public void writeTo(AbstractList list, Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> headers, OutputStream outputStream) throws IOException, WebApplicationException {
if (list.isEmpty())
outputStream.write(EMPTY_JSON_ARRAY.getBytes());
}
}
Nguồn
2016-01-08 19:52:21
JAX-RS/Jersey không hỗ trợ serialization các loại nguyên thủy hoặc thậm chí các loại trình bao như Integer, Boolean vv AFAIK, cách tiếp cận bạn đã thực hiện là cách duy nhất. –
OK, cảm ơn bạn! – Olvagor