将 JSON 从 Python 发送到 Java

Sending JSON from Python to Java

我正在尝试将 JSON 从 Python 客户端发送到 Java 服务器

JSON 数据类型是字节(在 Python 中),当我反序列化它(在 Python 中)并打印它时,它看起来很完美。当 Java 客户端连接时,服务器工作正常,当我反序列化 JSON 并在 Java 中打印它时,它看起来与 Python 和实际的 [=40] 完全一样=] 文件。 JSON 看起来一切正常,但 Java 服务器不接受数据。

data = open(file_path, 'r').read() # reading JSON object as string
serialized_data = pickle.dumps(data)

s.send(serialized_data)

当我发送 JSON 文件时,Java 服务器确认连接但 JSON 数据出于某种原因不被接受。

Java 客户

String sentence = new String(readFile());

if(!sentence.equals("fileNotFound")) {
    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
    oos.writeObject(sentence);
}

Java 服务器

ObjectInputStream inFromClient = new ObjectInputStream(socket.getInputStream());
String clientString = null;
try {
    clientString = (String) inFromClient.readObject();
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}
inFromClient.close();

You appear to be doing this:

  1. Read JSON from file as a String
  2. Pickle the string
  3. Send the pickle to Java.

That won't work. A pickle is a Python-specific serialization format. Java doesn't understand it.

The data you are reading from the file is already serialized .... as JSON.

Solution: send the string containing the JSON without pickling it.


On the other hand, if the Java server expects to receive something that has been serialized using ObjectOutputStream, then you have a bigger problem. The Java Object Serialization protocol is Java specific. Python doesn't support it. But if you are actually sending JSON to the server you should need to do that. Change the server to accept JSON, and get rid of the ObjectInputStream / ObjectOutputStream code on both sides.


On the third hand, if you can't get rid of the ObjectInputStream / ObjectOutputStream stuff, then maybe you need to modify the server side to either provide a separate API for python to call, or get the server to check the request's "content-type" header and handle either form of data serialization (JSON and Object Serialization protocol)