从spring控制器返回JSON字符串

时间:2016-05-12 06:52:59

标签: json ajax spring

我编写了一个服务,通过来自solr的AJAX调用进行查询,并将搜索结果作为json返回。我想把这个json从我的控制器返回到AJAX。

public class SearchServiceImpl implements SearchService {
private String getSearchResults(String url) throws ClientProtocolException,
            IOException {
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        HttpResponse response = client.execute(get);
        //logger.info("Response: " + response.getEntity().getContent());
         BufferedReader rd = new BufferedReader(new InputStreamReader(response
         .getEntity().getContent()));
         StringBuilder sb = new StringBuilder();
         String line = "";
         while ((line = rd.readLine()) != null) {
             sb.append(line);
         }
         return sb.toString();
    }

public String performSearch(String term) {
        String result = "";
        try {
            result = getSearchResults(getSolrURL(term)); // getSolrURL() prepares the solr url
        } catch (ClientProtocolException e) {
            logger.error(e);
        } catch (IOException e) {
            logger.error(e);
        }
        return result;
    }
}

这是我控制器中的handleRequest()方法 -

public ModelAndView handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        logger.info("Perform search view");
        String term = request.getParameter("term");
        String result = searchService.performSearch(term);
        // Here I need to return result which is a json
        ModelAndView mav = new ModelAndView(new MappingJackson2JsonView());
//      mav.addObject("key1", "value1"); 
//      mav.addObject("key2", "value2");
        return mav;

    }

1 个答案:

答案 0 :(得分:0)

最好的办法是让杰克逊自动完成所有序列化。所以你的控制器看起来像这样

@RequestMapping(value = "/payment/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody Payment get(@PathVariable Long id) {
            return paymentService.getById(id);
        }

支付类拥有杰克逊的所有吸气剂和制定者

package net.isban.example.vo;

    public class Payment {

    private Long id;

    private String sort;

    private String account;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getSort() {
        return sort;
    }

    public void setSort(String sort) {
        this.sort = sort;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    @Override
    public String toString() {
        return "Payment [id=" + id + ", sort=" + sort + ", account="
                + account + "]";
    }

}

并确保将Jackson纳入课程路径

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

这假设您正在使用Spring,否则您仍然可以使用Jackson生成json:

String json = new ObjectMapper().writeValueAsString(payment);