3

I am not sure why this is happening. My return statement for spring boot rest controller is something like below

return ResponseEntity.status(HttpStatus.OK).body("Successfully added");

Now on swagger UI i see response as below

can't parse JSON.  Raw result:

Successfully added

why is this happening ?

user9735824
  • 1,196
  • 5
  • 19
  • 36

4 Answers4

3

This is happening because you are returning a string literal instead of a JSON object. I presume your return type would have been ResponseEntity<String> but this would not work and you would need to specify an object in the body. You can create a POJO that will hold the message for you, something like this:

public class YourResponseClass {
    private String message;
    //Constructors, getter and setter
}

Then while returning you need to change the return type to ResponseEntity<YourResponseClass> and then return your response:

return ResponseEntity.ok(new YourResponseClass("Successfully Added."));
Sabir Khan
  • 9,826
  • 7
  • 45
  • 98
Shwetabh Shekhar
  • 2,608
  • 1
  • 23
  • 36
1

Late to the game but will share my solution to this issue, as it surfaced for me in a Python Flask-based REST backend I was developing recently. You could have NaN values in your JSON, if your issue was similar to mine, albeit in Python.

My underlying issue

I too was getting "can't parse JSON" on the swagger side. Turns out that Python's standard library json import will allow "modern" but not-officially-JSON types, such as "NaN". And doing some calculations with floats and voila...As a strict parser fails with a type such as NaN, it's worth checking that you don't have these in your request JSON response.

Solved it with an encoder class

Though not a Java-specific answer, maybe my Python solution can help you solve the issue.

json.dumps(yourdata, cls=NumpyEncoder)

Where NumpyEncoder is some class that converts NaN values to JSON and/or your acceptable specifications. It might be the case that you too can include some encoder class in your code to remove NaN and/or other artifacts.

See my so answer for Python implementation details.

Jason R Stevens CFA
  • 2,232
  • 1
  • 22
  • 28
  • "NaN" values was exactly my problem. Got rid of them with `df.fillna("")` and it worked like a charm. – kchomski Oct 01 '20 at 23:26
0

It is hard to say without seeing more code and the actual Swagger JSON, but it seems like the JSON has a syntax issue. Run it through a JSON validator to confirm. There are plenty of websites for this if you Google it.

HenryTK
  • 1,287
  • 8
  • 11
-2

The response type should be "text/plain" (produces = "MediaType.TEXT_PLAIN")

Googlian
  • 6,077
  • 3
  • 38
  • 44
Riju
  • 7
  • 3