我尝试使用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
}
}