Spring MVC准备JSON但是加载页面

时间:2017-09-16 17:52:51

标签: json spring spring-mvc gson

我有一个控制器来发回JSON Payload

    @RequestMapping(value = "/MerchantMonitoringAPI", method = RequestMethod.GET,produces = "application/json") 
public String MerchantMonitoring() {

    ApplicationContext context =
            new ClassPathXmlApplicationContext("Spring-Module.xml");

        TopMerchantsDAO topMerchantsDAO = (TopMerchantsDAO) context.getBean("topMerchantsDAO");
        TopMerchants topMerchants = topMerchantsDAO.retrieveMerchantList();

        for(String temp:topMerchants.getMerchantList())
        {
            System.out.println(temp);
        }

        Gson gson = new Gson();
        Type type = new TypeToken<TopMerchants>() {}.getType();

        String jsonPayload = gson.toJson(topMerchants, type);
        System.out.println(jsonPayload);

        return jsonPayload;
}

它试图将我的名称重定向到一个视图,其中页面名称为JSON(localhost:8080 / {&#34; merchantList&#34;:[&#34; Apple&#34;,&#34; Google&# 34;]} JSP)

如何停止并返回JSON有效负载??

2 个答案:

答案 0 :(得分:2)

在@RequestMapping

之上添加@RestController
    @RestController 
    @RequestMapping(value = "/MerchantMonitoringAPI", method = 
    RequestMethod.GET,produces = "application/json") 
    public String MerchantMonitoring() {...}

由于该方法现在使用@RestController进行注释,因此从此方法返回的对象将通过消息转换为客户端生成json资源表示。

答案 1 :(得分:0)

如果您想在同一个班级中使用多种方法返回 JSON ,您仍然可以使用@Controller为您的班级注释,方法对于使用@ResponseBody

注释的JSON

如果您将使用@RestController注释类 - 类中的所有方法都将像@ResponseBody一样工作,类将类似@Controller注释。当然,这是一种更好的方法(在一个Controller中不包括页面和JSON返回方法)。

注意!您只能将@RestController用于课程(而不是@Controller),而不能用于方法。 如果你打开这个注释的来源,你会看到下一个:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
    String value() default "";
}

ElementType.TYPE有评论:

  

类,接口(包括注释类型)或枚举声明