我正在尝试创建一个自定义BodyPublisher来反序列化我的 JSON 对象。我可以在创建请求时反序列化 JSON 并使用 的ofByteArray方法,BodyPublishers但我宁愿使用自定义发布者。
public class CustomPublisher implements HttpRequest.BodyPublisher {
private byte[] bytes;
public CustomPublisher(ObjectNode jsonData) {
...
// Deserialize jsonData to bytes
...
}
@Override
public long contentLength() {
if(bytes == null) return 0;
return bytes.length
}
@Override
public void subscribe(Flow.Subscriber<? super ByteBuffer> subscriber) {
CustomSubscription subscription = new CustomSubscription(subscriber, bytes);
subscriber.onSubscribe(subscription);
}
private CustomSubscription implements Flow.Subscription {
private final Flow.Subscriber<? super ByteBuffer> subscriber;
private boolean cancelled;
private Iterator<Byte> byterator;
private …Run Code Online (Sandbox Code Playgroud)