2017-08-18 33 views
0

在spring引导中可以使用@produces作为JSON对象吗?还是有实现这个法子:如何在JSON对象中使用@produces spring引导

JSONObject J_Session = new JSONObject(); 
J_Session.put("SESSION_ID_J", session_jid); 
J_Session.put("J_APP", "J"); 
J_Session.put("REST_ID_J", rest_id); 
+0

您能否详细说明这个问题,您只是想知道您是否可以使用'@ Produces'注释在Spring rest API中提供json响应? – Chaitanya

+0

使用POJO。他们应该被默认支持。 –

+0

@Chaitanya是的就是这样。你能举个例子吗 –

回答

0

下面是一个简单的例子:

RestController class: 


import java.util.ArrayList; 
import java.util.List; 

import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RestController; 

import com.websystique.springboot.model.User; 

@RestController 
@RequestMapping("/api") 
public class RestApiController { 

    @RequestMapping(value = "/user/", method = RequestMethod.GET, produces = { "application/json" }) 
    public List<User> listAllUsers() { 
     List<User> users = new ArrayList<User>(); 
     users.add(new User(1, "Sam", 30, 70000)); 
     users.add(new User(2, "Tom", 40, 50000)); 
     users.add(new User(3, "Jerome", 45, 30000)); 
     users.add(new User(4, "Silvia", 50, 40000)); 
     return users; 
    } 
} 

属性produces = { "application/json" }列表集合将自动转换为JSON响应。

以下是POJO课程。

User Pojo class 


public class User { 

    private long id; 

    private String name; 

    private int age; 

    private double salary; 

    public User(){ 
    } 

    public User(long id, String name, int age, double salary){ 
     this.id = id; 
     this.name = name; 
     this.age = age; 
     this.salary = salary; 
    } 
} 

样品JSON响应:

[ 
    { 
     "id":1, 
     "name":"Sam", 
     "age":30, 
     "salary":70000 
    }, 
    { 
     "id":2, 
     "name":"Tom", 
     "age":40, 
     "salary":50000 
    }, 
    { 
     "id":3, 
     "name":"Jerome", 
     "age":45, 
     "salary":30000 
    }, 
    { 
     "id":4, 
     "name":"Silvia", 
     "age":50, 
     "salary":40000 
    } 
] 

关注这个link与CRUD操作的完整详细的例子。

上面的代码是从这个链接本身,我只是修改控制器部分,使其简单。