Spring-Returning json with @ResponseBody when the Accept header is */* throws HttpMediaTypeNotAcceptableException

后端 未结 3 806
情深已故
情深已故 2021-01-07 02:00

I\'m using spring 3.0.0.

I have an endpoint that returns an object that I want to be serialized to JSON. When the request comes in with Accept: application/json, it

3条回答
  •  一整个雨季
    2021-01-07 02:27

    I just ran into this same issue. I'm not sure if its more elegant but what I've chosen to do is to just return a string, and convert the object to Json myself. I decided to use Gson for the JSON library.

    @Controller
    public class NewAbstractController  {
    
       @RequestMapping(value = "/simple", method = RequestMethod.GET)
       public @ResponseBody String SayHello()
       {
           Foo foo = new Foo();
           foo.Name = "Chris";
           foo.age = 30;
    
           Gson gson = new Gson();
           return gson.toJson(foo);
       }
    
       public class Foo implements Serializable
       {
           public String Name;
           public Integer age;
       }
    
    }
    

提交回复
热议问题