天天看點

反序列化 ServiceHealth 時遇到的問題

寫UT的時候跟consul互動的部分需要打樁處理,顧嘗試把從consul傳回的 List<ServiceHealth > 序列化以後json 寫入檔案,然後test case中反序列化成List<ServiceHealth>。

但是萬萬沒想到,序列化沒什麼問題,但反序列化時報異常:

Can not find a deserializer for non-concrete Collection type [collection type; class com.google.common.collect.ImmutableList, contains [simple type, class com.orbitz.consul.model.health.HealthCheck]]
           

Stack Overflow上有人說是沒有添加 GuavaModule導緻的。然而并不知道怎麼加。

然後去github 上找到 jackson-datatypes-collections 的項目,仿照作者寫的UT,改了一下

ObjectMapper mapper = new ObjectMapper();

改成 

ObjectMapper mapper = new Jackson2ObjectMapperBuilder().build().registerModule(new GuavaModule().configureAbsentsAsNulls(false));
           

然後報類型不比對 (List<ServiceHealth> 序列化出來的json)

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
           

對比log和json發現

Checks 下的Notes,Output,ServiceID,ServiceName 都必須是String 類型,但 序列化出來的是個Object 

使用curl 指令直接從consul上取得json

curl localhost:8500/v1/health/service/<serviceName>

得到的json 複制粘貼到檔案裡,然後就反序列化成功了