我想使用通用模型通过 websocket 从服务器到客户端广播不同的数据。不幸的是,我在想要序列化以下类结构时总是遇到错误:
使用 SimpleJson 序列化的类:
public class UpdateBroadcastMessageData {
private List<UpdateBroadcastModel<? extends Object>> models = new ArrayList<UpdateBroadcastModel<? extends Object>>();
public void clearModels() {
...
}
public void addModel(Object model) {
...
}
public void removeModel(Object model) {
...
}
}
public class UpdateBroadcastModel<T extends Object> {
private String clazz = null;
private T payload = null;
...
}
我的 JsonUtil 类总是抛出消息“无法转换为 JSon”。
import org.codehaus.jackson.map.ObjectMapper;
public class JsonUtil {
private static ObjectMapper mapper = new ObjectMapper();
public static String convertToJson(Object object) {
try {
return mapper.writeValueAsString(object);
} catch (Exception e) {
log.error("Could not convert Object to JSON", e);
return "";
}
}
public static <T> T convertToObject(String json, Class<T> clazz) {
try {
return mapper.readValue(json, clazz);
} catch (Exception e) {
log.error("Could not convert JSON to Object", e);
return null;
}
}
}
有人可以帮助我并告诉我该怎么做才能序列化上述数据结构吗?
该错误是指 converttoJson 方法。这是堆栈跟踪:
ERROR [pool-3-thread-1][JsonUtil:16] Could not convert Object to JSON
org.codehaus.jackson.map.JsonMappingException: No serializer found for class
...UpdateBroadcastMessageData and no properties discovered to create BeanSerializer
(to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) )
at org.codehaus.jackson.map.ser.StdSerializerProvider$1.serialize(StdSerializerProvider.java:62)
at org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:296)
at org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:224)
at org.codehaus.jackson.map.ObjectMapper._configAndWriteValue(ObjectMapper.java:1512)
at org.codehaus.jackson.map.ObjectMapper.writeValueAsString(ObjectMapper.java:1262)
at ...JsonUtil.convertToJson(JsonUtil.java:14)
at ...CommitPoiTokenAction.doProcess(CommitPoiTokenAction.java:118)
at ...BaseWebSocketTokenAction.processMessage(BaseWebSocketTokenAction.java:29)
at ...WebSocketListener$1.run(WebSocketListener.java:145)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
pool-3-thread-1: code=81 len=118
提前致谢。法科