Bây giờ tôi đang làm việc với Jackson và tôi có một số câu hỏi về nó.Json deserialization vào một hệ thống phân cấp lớp khác bằng cách sử dụng Jackson
Trước hết. Tôi có hai dịch vụ, đầu tiên là thu thập dữ liệu và gửi dịch vụ và thứ hai nhận dữ liệu này và, ví dụ, đăng nhập vào một tệp.
Vì vậy, dịch vụ đầu tiên có hệ thống phân cấp lớp như thế này:
+----ConcreteC
|
Base ----+----ConcreteA
|
+----ConcreteB
Và thứ hai dịch vụ có hệ thống phân cấp lớp như thế này:
ConcreteAAdapter extends ConcreteA implements Adapter {}
ConcreteBAdapter extends ConcreteB implements Adapter {}
ConcreteCAdapter extends ConcreteC implements Adapter {}
Các dịch vụ đầu tiên không biết gì về ConcreteXAdapter
.
Cách tôi đang gửi dữ liệu trên dịch vụ đầu tiên:
Collection<Base> data = new LinkedBlockingQueue<Base>()
JacksonUtils utils = new JacksonUtils();
data.add(new ConcreteA());
data.add(new ConcreteB());
data.add(new ConcreteC());
...
send(utils.marshall(data));
...
public class JacksonUtils {
public byte[] marshall(Collection<Base> data) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream() {
@Override
public byte[] toByteArray() {
return buf;
}
};
getObjectMapper().writeValue(out, data);
return out.toByteArray();
}
protected ObjectMapper getObjectMapper() {
return new ObjectMapper();
}
public Object unmarshall(byte[] json) throws IOException {
return getObjectMapper().readValue(json, Object.class);
}
public <T> T unmarshall(InputStream source, TypeReference<T> typeReference) throws IOException {
return getObjectMapper().readValue(source, typeReference);
}
public <T> T unmarshall(byte[] json, TypeReference<T> typeReference) throws IOException {
return getObjectMapper().readValue(json, typeReference);
}
}
Vì vậy, tôi muốn desirialize json vào Bộ sưu tập của ConcreteXAdapter
, không vào Bộ sưu tập của ConcreteX
(ConcreteA -> ConcreteAAdapter, ConcreteB -> ConcreteBAdapter, ConcreteC -> ConcreteCAdapter
). Trong trường hợp tôi mô tả tôi muốn nhận được:
Collection [ConcreteAAdapter, ConcreteBAdapter, ConcreteCAdapter]
Làm cách nào tôi có thể thực hiện việc này?
Cảm ơn bạn đã trả lời nhanh chóng! Tôi đã cập nhật câu hỏi. Tóm lại, dịch vụ đầu tiên không biết gì về 'ConcreteXAdapter'. Vì vậy, câu hỏi là làm thế nào để nói với Jackson để tạo ra 'ConcreteXAdapter' nếu nó tìm thấy' ConcreteX' trong json. – pbespechnyi
Trong trường hợp này, tôi khuyên bạn nên chuyển kiểu bằng tay (như "@type": "ConcreteA") và sau đó deserialize ở phía bên kia dựa trên thuộc tính. I E. bạn cần phải thực hiện một serializer tùy chỉnh cho việc này. –
Vì vậy, không có cách nào để làm điều này ra khỏi hộp. Ok, cảm ơn vì sự giúp đỡ! – pbespechnyi