0

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();       
    }
}
Cœur
  • 32,421
  • 21
  • 173
  • 232
Sasha
  • 1,100
  • 2
  • 12
  • 23

2 Answers2

1

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.

Community
  • 1
  • 1
Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
-1

Can you try using json format as follows:

public class objectOutput {

static int i=0;
PrintWriter pw;

public objectOutput(HttpServletResponse response)  throws IOException {

    response.setContentType("application/json");
    pw = response.getWriter();  

}

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

    pw.print(object);
    pw.flush();      
    pw.close(); 
}

}
additionster
  • 598
  • 3
  • 13