Spring MVC -> JSON response

前端 未结 5 1793
太阳男子
太阳男子 2020-12-05 08:51

I hava a JAVA EE backend and I am using Spring MVC. I have a AJAX call like this:

function getAllProjects() {
        $.getJSON(\"project/getall\", function(         


        
相关标签:
5条回答
  • 2020-12-05 09:04

    You can also use org.json's JSONArray and JSONObject to construct the JSON output, then, return a String value as the @ResponseBody.

    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();
    }
    

    You should get something like this in your ajax request's success callback.

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

    You can use this data to either append your ul li using javascript or using _underscore templating to render your UI.

    0 讨论(0)
  • 2020-12-05 09:05

    You need to:

    • Add Jackson JSON Mapper to the classpath
    • Add <mvc:annotation-driven> to your config
    • Return Map<Integer, String>

    For more complex cases when you need to configure mapping process for each handler method you may use MappingJacksonJsonView instead of @ResponseBody, as Stepen C suggested.

    0 讨论(0)
  • 2020-12-05 09:05

    The rest of these answers are extremely out-of-date! It's very easy now

    • add Jackson2 to your classpath
    • use @RestController

    ex:

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

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

    0 讨论(0)
  • 2020-12-05 09:11

    As suggested here: Spring 3 JSON with MVC checkout this website: http://spring-json.sourceforge.net/ It has perfectly nice working example on how to do this in spring framework.

    0 讨论(0)
  • 2020-12-05 09:16

    You need to read Chapter 15.5 of the Spring User Guide which describes how to configure MVC views, and Chapter 16.10 which briefly describes the JSON Mapping View. Then read the javadocs for MappingJacksonJsonView etc.

    0 讨论(0)
提交回复
热议问题