WebSocket(二):传递对象

如果直接使用websocket中的javax.websocket.Session.getBasicRemote().sendObject(map)传递对象,会报如下错误

javax.websocket.EncodeException: No encoder specified for object of class [class org.********]

应该写一个编码器


import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;

import org.codehaus.jackson.map.ObjectMapper;

public class EncoderClassVo implements Encoder.Text<Map<String, List>>{

    @Override
    public void init(EndpointConfig config) {
        // TODO Auto-generated method stub

    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }
//我向web端传递的是Map类型的
    @Override
    public String encode(Map map) throws EncodeException {
        ObjectMapper    mapMapper= new ObjectMapper();
        try {
            String json="";
            json=mapMapper.writeValueAsString(map);
            return  json;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "false";
        }
    }
//如果你传递的是一个类,则使用如下写法
    @Override  
    public String encode(Person person) throws EncodeException {  
        try {  
            return Java2Json.JavaToJson(person, false);  
        } catch (MapperException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
            return null;  
        }  
    }  

}

你可能感兴趣的:(WebSocket)