I'm trying to send JSON from a Python client to a Java server
The JSON data type is bytes (in Python) and when I deserialize it (in Python) and print it, it looks perfect. The server works fine when a Java client connects and when I deserialize the JSON and print it in Java it looks exactly the same as in Python and the actual JSON files. The JSON all looks good, but the data isn't accepted by the Java server.
data = open(file_path, 'r').read() # reading JSON object as string
serialized_data = pickle.dumps(data)
s.send(serialized_data)
When I send a JSON file the Java server acknowledges the connection but the JSON data for whatever reason isn't accepted.
Java Client
String sentence = new String(readFile());
if(!sentence.equals("fileNotFound")) {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(sentence);
}
Java Server
ObjectInputStream inFromClient = new ObjectInputStream(socket.getInputStream());
String clientString = null;
try {
clientString = (String) inFromClient.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
inFromClient.close();
1 Answer 1
You appear to be doing this:
- Read JSON from file as a String
- Pickle the string
- 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)
7 Comments
s.send(value.encode()) The data is sent as a string but still no joy.Explore related questions
See similar questions with these tags.
picklein your code?content-typeissue.print(s.send(value))I get a number back. The server should accept whatever, it's coded to accept JSON, XML or text