ObjectOutputStream: appending question marks at the beginning of the String

Server(Java) sends a Json String to a client(TypeScript). On the client I get the following: enter image description here

Therefore JSON.parse() fails due to question marks being appended.

I tried:

  1. Setting content type to - "text/html"
  2. Setting encode to - "UTF-8"

And nothing seem to remove these.

My code:

public class objectOutput {

    static int i=0;
    ObjectOutputStream objectOutputStream;

    public objectOutput(HttpServletResponse response)  throws IOException {

        response.setContentType("application/octet-stream");
        objectOutputStream = new ObjectOutputStream(response.getOutputStream());  

    }

    // Using this method to write a Json String
    public void writeObject(Object object) throws IOException {

        objectOutputStream.writeObject(object);
        objectOutputStream.close();
        objectOutputStream.flush();       
    }
}
Jon Skeet
people
quotationmark

Basically, you shouldn't be using ObjectOutputStream if you're just trying to send text. That's not what it's for. ObjectOutputStream performs binary serialization in a Java-specific format, of arbitrary serializable objects. It should only be used when the code reading the data is also Java, using ObjectInputStream.

In this case, you should probably just call response.getWriter() instead, or create an OutputStreamWriter around response.getOutputStream() yourself. (Using getWriter() is generally preferred here - the whole point of that call is to create a writer for text responses.)

The content type is unrelated to this problem, but you should probably change that to application/json.

people

See more on this question at Stackoverflow