2014-09-06 2 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 결과를 저장합니다. 이 목적으로 고려되는 테스트 및 웹 서비스 문제는 아닙니다. 그 어떤 생각? 미리 감사드립니다.

+0

질문이 이해가 가지 않습니다. 이걸 어디에서하고 싶니? 특수 효과를 적용한 후 무엇을 의미합니까? –

답변

0

pom.xml에 jackson 종속성을 지정하지 않는 것이 좋습니다.

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

는 또한 당신은 수동으로 ResponseEntity를 통해 반환하기 전에 JSON에 결과를 직렬화 컨트롤러에 잭슨의 ObjectMapper를 주입 할 수있는이

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

모든 것이 잘 작동하며 브라우저의 JSON 결과를 얻을 수 있습니다. 하지만 브라우저가 아닌 자바 코드에 컨트롤러 결과를 저장하고 싶습니다. – Khodabakhsh

+0

로그 파일에 인쇄 하시겠습니까? 세션을 계속 유지하려고합니까? "저장 중"이라고하는 것 –

+0

Gson gson = new Gson(); String jsonResponse = gson.toJson (result); 이 원하는 경우 json String을 제공 할 수 있습니다. –

1

같은 요청 매핑을 업데이트 할 수 있습니다.

@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을 전달하고 JSON 결과를 얻고 싶습니다. – Khodabakhsh