Announcement Announcement Module
No announcement yet.
ExceptionHandler: How to return a JSON object? Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • ExceptionHandler: How to return a JSON object?

    I am in Jetty (though I am not sure that's actually relevant).

    The objective is to return a specific HTTP error code (which is contained in the exception object), the right JSON payload (an description of the error) with the appropriate Content-Type etc.

    This doesn't appear possible. I have tried:
    - return a regular object just I do in my controller methods hoping it will get mapped to JSON - that fails it can't find the right mapper
    - return a ModelAndView that maps to a freemarker page with a single $json variable - sort of works but it's ghetto and returns the wrong content type
    - do everything in the handler (set the content type, get the output stream, jam the JSON down the stream and flush, return void) and the page that gets returned is still the JSON error page (with the stuff I cram down the stream)

    I'd love to figure out what the right way is to handle this.


  • #2
    Why do you choose a freemarker view with a $json instead of a JsonView?


    • #3
      Hey, thanks for the pointer.

      I didn't realize that we could still use a JSON view, the same way it was used in 2.5 with the new support.


      <bean name="xmlViewResolver" class="org.springframework.web.servlet.view.XmlVie wResolver">
      <property name="order" value="1"/>
      <property name="location" value="/WEB-INF/json-views.xml"/>


      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "">


      <bean name="jsonView" class="org.springframework.web.servlet.view.json.M appingJacksonJsonView"/>


      in json-views.xml did the trick.



      • #4
        There is an additional question, which is that I return:

        return new ModelAndView("jsonView", "envelope", envelope);

        Ideally, I would just like the envelope as the top-level JSON object. As it is, it returns { envelope={<attribute list>}}

        I'd like to get the <attribute list> as the top-level json object. passing "" as the model name doesn't see to work.