Khoda
Khoda

Reputation: 953

How to get JSON result of a mapped URL

Suppose we have the following controller

@Controller
@RequestMapping("/Index")
public class ControllerClass {

  @RequestMapping("/Result")
  @ResponseBody
  public List<Integer> result(){
     List<Integer> result = new ArrayList<Integer>();
     result.add(1);
     result.add(2);
     return result;
  }
 }

Now I want to store the JSON result of the URL "/Index/Result" into a string. or simply, store the JSON result of controller after applying the annotations. note that it's not for testing and webservice matter considered for this purpose. any idea for that? Thanks in advance.

Upvotes: 0

Views: 109

Answers (2)

Ricardo Veguilla
Ricardo Veguilla

Reputation: 3155

You can inject Jackson's ObjectMapper into the controller to manually serialize the result to JSON before returning via an ResponseEntity.

@Configuration
public class Config {

     @Bean
     public ObjectMapper objectMapper() {
         // returning a plain ObjectMapper, 
         // you can change this to configure the ObjectMapper as requiered
         return new ObjectMapper();
     }
}


@Controller
@RequestMapping("/Index")
 public class ControllerClass {

   @Autowired
   private ObjectMapper objectMapper;

   @RequestMapping(value="/Result", 
                   method=RequestMethod.GET, 
                   produces="application/json")
   @ResponseBody
   public ResponseEntity<String> result(){
     List<Integer> result = new ArrayList<Integer>();
     result.add(1);
     result.add(2);
     String jsonResult = objectMapper.writer().writeValueAsString(result);
     // here you can store the json result before returning it;
     return new ResponseEntity<String>(jsonResult, HttpStatus.OK);
   }
}

Edit:

You can also try defining an HandlerInterceptor that captures the response body for the request you are interested.

@Component
public class RestResponseInterceptor implements HandlerInterceptor {

      public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
          // inspect response, etc...
     }
}

Upvotes: 1

Sezin Karli
Sezin Karli

Reputation: 2525

I suggest to put jackson dependencies in your pom.xml if they are not already there.

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.2.3</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.2.3</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.2.3</version>
    </dependency>

You can also update your request mapping like this

@RequestMapping(value = "/Result", produces = "application/json;charset=utf-8")

Upvotes: 0

Related Questions