2017-08-18 29 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操作的完整詳細的例子。

上面的代碼是從這個鏈接本身,我只是修改控制器部分,使其簡單。