2014-09-06 59 views
0

假設我們有以下的控制器如何獲得一個映射的URL的JSON結果

@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; 
    } 
} 

現在我想保存URL「/索引/結果」爲一個字符串的JSON結果。或者乾脆在應用註釋之後存儲控制器的JSON結果。請注意,它不適用於爲此目的考慮的測試和Web服務事宜。任何想法? 在此先感謝。

+0

我不明白你的問題。你想要做什麼?你在申請annotations_之後是什麼意思_? – 2014-09-06 17:13:19

回答

0

我建議把傑克遜依賴項放入你的pom.xml中,如果它們不在那裏的話。

<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> 

您還可以更新您的要求這樣的映射

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

一切正常,我可以在瀏覽器中獲取URL的JSON結果。但我想將控制器結果存儲在java代碼中,而不是在瀏覽器中。 – Khodabakhsh 2014-09-06 13:52:28

+0

你想把它打印到日誌文件?或者你希望它堅持會話?你的意思是「存儲」 – 2014-09-06 13:55:11

+0

Gson gson = new Gson(); String jsonResponse = gson.toJson(result); 可以給你json字符串,如果這是你想要的 – 2014-09-06 13:57:19

1

你可以注入傑克遜的ObjectMapper到控制器通過一個ResponseEntity返回之前的結果手動序列化到JSON

@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); 
    } 
} 

編輯

您也可以嘗試定義HandlerInterceptor捕獲響應主體對你有興趣的請求。

@Component 
public class RestResponseInterceptor implements HandlerInterceptor { 

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

謝謝你。但問題是,我想將一個URL傳遞給servlet並獲取JSON結果,而不向控制器或任何服務器端類添加任何內容。 – Khodabakhsh 2014-09-13 06:30:04