spring mvc rest response json and xml

后端 未结 7 1926
無奈伤痛
無奈伤痛 2020-12-28 19:24

I have the requirement to return the result from the database either as a string in xml-structure or as json-structure. I\'ve got a solution, but I don\'t know, if this one

7条回答
  •  余生分开走
    2020-12-28 20:12

    Easiest way to do this to get JSON response would be: Using Spring 3.1, you could do as follows

    1. In your pom.xml file (hoping you are using a maven project), add maven dependency for jackson-mapper (http://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl/1.9.13)

    2. Modify your code as follows and test the endpoint on postman:

      @RequestMapping(value = "/content/json/{ids}", method = RequestMethod.GET)
      public @ResponseBody String getContentByIdsAsJSON(@PathVariable("ids") String ids){
          String content = "";
          StringBuilder builder = new StringBuilder();
      
          List list = this.contentService.findContentByListingIdAsJSON(ids);
          if (list.isEmpty()){
              content = "no data found";
              return content;
          }
          for (String json : list){
              builder.append(json + "\n");
          }
      
          content = builder.toString();
          return content;
      }
      

提交回复
热议问题