[英]cannot convert a zookeeper object to json and vice versa
大家好,我有一個簡單的問題,我似乎無法使用澤西島的GSON庫為Java Web服務將Zookeeper對象轉換為json,反之亦然。我得到的錯誤是
Exception in thread "main" java.lang.StackOverflowError
at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:381)
at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:376)
at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:381)
at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:376)
而且它還在繼續發展。 根據我的搜索,這個問題就是嵌套對象和遞歸太深的問題。 這是我為簡單的POC嘗試的方法
ZooKeeper zoo;
try {
zoo = new ZooKeeper("localhost:2182",5000,null);
String obj=gson.toJson(zoo, ZooKeeper.class);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
有人可以清楚地說明什么是實際問題,即使有可能將zookeeper對象轉換為json並使用(因為與之相關的所有線程)
ZooKeeper是服務器而不是DTO
也許你想用DTO配置做一個json
我的主張
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:
為ClientCnxn創建TypeAdapter
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.