ZooKeeper - это сервер, а не DTO
, может быть, вы хотите сделать JSON с конфигурацией DTO
мое предложение
public static void main(String[] args) {
ZooKeeper zoo;
try {
ZooKeeperConfDTO conf = new ZooKeeperConfDTO("localhost:2182", 5000, null);
zoo = runZoo(conf);
String json = new Gson().toJson(conf);
System.out.println(json); //---->{"connectString":"localhost:2182","sessionTimeout":5000}
} catch (Exception e) {
e.printStackTrace();
}
}
private static ZooKeeper runZoo(ZooKeeperConfDTO conf) throws IOException {
return new ZooKeeper(conf.connectString, conf.sessionTimeout, conf.watcher);
}
и созданный класс
import org.apache.zookeeper.Watcher;
public class ZooKeeperConfDTO {
public String connectString;
public int sessionTimeout;
public Watcher watcher;
public ZooKeeperConfDTO(String connectString, int sessionTimeout, Watcher watcher) {
this.connectString = connectString;
this.sessionTimeout = sessionTimeout;
this.watcher = watcher;
}
}
версия 2:
создайте свой TypeAdapter для ClientCnxn
import java.io.IOException;
import org.apache.zookeeper.ClientCnxn;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
public class ClientCnxnAdapter extends TypeAdapter<ClientCnxn> {
@Override
public void write(JsonWriter writer, ClientCnxn cnxn) throws IOException {
writer.beginObject();
writer.name("sessionId");
writer.value(cnxn.getSessionId());
writer.name("timeOut");
writer.value(cnxn.getSessionTimeout());
writer.endObject();
}
@Override
public ClientCnxn read(JsonReader in) throws IOException {
return null;
}
}
и используйте его
public static void main(String[] args) {
ZooKeeper zoo;
try {
zoo = new ZooKeeper("localhost:2182", 5000, null);
Gson gson = new GsonBuilder().registerTypeAdapter(ClientCnxn.class, new ClientCnxnAdapter()).create() ;
String json = gson.toJson(zoo);
System.out.println(json); //---->{"cnxn":{"sessionId":0,"timeOut":0},"watchManager":{"dataWatches":{},"existWatches":{},"childWatches":{}}}
} catch (Exception e) {
e.printStackTrace();
}
}