序列化,反序列化arraylist <t>

时间:2016-09-11 22:03:05

标签: java json sockets gson

我尝试使用gson通过套接字发送序列化数据。问题是,当我尝试deserialize时,它会给我以下错误

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 47

ClientSocket我序列化的地方:

public static void client(String ip, int port) throws IOException {
  try {
    ArrayList<Sensor> updatedSensorList = createSensor.getInstance().getSensorList();
     Gson gson = new Gson();
       Socket clientSocket = new Socket(ip, port);
        Type collectionType = new TypeToken<ArrayList<Sensor>>() {
            }.getType();

      DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
      String message = gson.toJson(updatedSensorList,collectionType);
       outToServer.writeBytes(message);
        clientSocket.close();
        } catch (IOException e) {
            System.out.println("Could not listen on port " + port);
        }
    }

我尝试反序列化的ServerSocket端

public class server extends Thread {

        private BufferedReader inFromClient;
        private Socket connectionSocket;
        ArrayList<gateway.Sensor> sensorList;
        int position, nextPort;

        public receivedMessages(Socket socket) {
            connectionSocket = socket;

        }

        @Override
        public void run() {
            try {
             InputStreamReader inFromClient = new InputStreamReader(connectionSocket.getInputStream());
             Type collectionType = new TypeToken<ArrayList<Sensor>>(){}.getType();
                ArrayList<Sensor> sensorList = new Gson().fromJson(inFromClient, collectionType);        
            ////othercode 
       }
    }

0 个答案:

没有答案