代码之家  ›  专栏  ›  技术社区  ›  Tim

Spring MVC->JSON响应

  •  13
  • Tim  · 技术社区  · 15 年前

    我有一个JavaEE后端,我使用Spring MVC。我有一个这样的Ajax调用:

    function getAllProjects() {
            $.getJSON("project/getall", function(allProjects) {
                ???
            });
        }
    

    我的后端系统:

    @RequestMapping(value="/getall", method=RequestMethod.GET)
    public @ResponseBody ??? getAllProjects() {
        ???
    }
    

    我必须实现的内容是什么,这样它才能工作?在后端系统中,我从数据库调用了唯一的ID和项目名称,例如:

    1 => My Test Project
    4 => Another One
    23 => One More Test
    

    ID和项目名称应该返回到前端系统,所以我可以用这种方式构建一个HTML ul/li列表:

    <ul>
        <li><a href="/1">My Test Project</a></li>
        <li><a href="/4">Another One</a></li>
        <li><a href="/23">One More Test</a></li>
    </ul>
    

    有人知道怎么做吗?

    5 回复  |  直到 11 年前
        1
  •  14
  •   axtavt    15 年前

    MappingJacksonJsonView @ResponseBody

        2
  •  8
  •   Stephen C    15 年前

    MappingJacksonJsonView

        3
  •  8
  •   severedsea    13 年前

    http://www.json.org/javadoc/org/json/JSONObject.html

    @RequestMapping(value="/getall", method=RequestMethod.GET)
    public @ResponseBody String getAllProjects() {
        ...
        JSONArray jsonItems = new JSONArray();
    
        JSONObject jsonItem1 = new JSONObject();
        jsonItem1.put("id", "1");
        jsonItem1.put("name", "My Test Project");
    
        JSONObject jsonItem2 = new JSONObject();
        jsonItem2.put("id", "4");
        jsonItem2.put("name", "Another one");
    
        jsonItems.put(jsonItem1);
        jsonItems.put(jsonItem2);
    
        return jsonItems.toString();
    }
    

    [{
       "id":"1",
       "name":"My Test Project"
    },{
       "id":"4",
       "name":"Another one"
    }]
    

        5
  •  1
  •   John Culviner    11 年前

    • @RestController

    @RestController
    public class MyController {
    
        @RequestMapping("/thing")
        public MyThing thing() {
            return new MyThing();
        }
    
    }
    

    http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-write-a-json-rest-service