2016-01-24 152 views
0

我正在使用Jersey框架並試圖返回{"status":201}作爲響應,但我得到{"status":201,"route":0}在momenat。我在另一個回覆中需要SDBeanPost課程中的路線和方向,但不是全部回覆。因此,我可以通過添加此行來刪除響應方向bean.direction = null;,但是我不知道如何從中刪除route從JSON響應中刪除密鑰

Receiver類

package org.busTracker.trackingService; 

/* 
* Inside this class, the request from the Android application - PostData class is received. 
* Consequently, a response is sent back. 
*/ 

import javax.ws.rs.Consumes; 
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response; 

@Path("/data") 
public class Receiver { 
    static String flagD; 

    @POST 
    @Consumes(MediaType.APPLICATION_JSON) 
    public Response proccessData(Data data) { 

     Database db = new Database(); 

     String macD = data.getMac(); 
     int routeD = data.getRoute(); 
     double latD = data.getLatitude(); 
     double longD = data.getLongitude(); 
     String timeD = data.getTime(); 
     int speedD = data.getSpeed(); 
     String directionD = data.getDirection(); 
     flagD = data.getFlag(); 

     // Jackson class to wrapper the data as JSON string. 
     SDBeanPost bean = new SDBeanPost(); 
     bean.direction = null;  
     bean.status = 201; 

     return Response.status(bean.status).entity(bean.toJson()).build(); 

    } 

} 

SDBeanPost

package org.busTracker.trackingService; 

/* 
* Class to wrap the response for the Receiver class. 
*/ 

import com.fasterxml.jackson.annotation.JsonInclude; 
import com.fasterxml.jackson.core.JsonProcessingException; 
import com.fasterxml.jackson.databind.ObjectMapper; 

//To return status without route null. 
@JsonInclude(JsonInclude.Include.NON_NULL) 
public class SDBeanPost { 

    public int status; 
    public int route; 
    public String direction; 

    public SDBeanPost() { 
     Receiver receiver = new Receiver(); 

     direction = ""; 
     status = 230; 

    } 

    public String toJson() { 

     ObjectMapper mapper = new ObjectMapper(); 
     String json = null; 
     try { 
      json = mapper.writeValueAsString(this); 
     } catch (JsonProcessingException e) { 
      e.printStackTrace(); 

     } 
     return json; 
    } 

} 
+1

爲什麼你返回一個SDBeanPost的實例,它有一個狀態,一個路線和一個方向,因爲你實際上只想返回一個狀態?使用不同的班級,其中有你想要的字段,只有那些字段。另外,請勿自行序列化爲JSON。澤西爲你做到了這一點。在身體中返回身份也是可疑的,順便說一句。 HTTP響應已經具有狀態。所以,除非身體狀態是一種完全不同的狀態,否則它不應該在身體中。 –

回答

3

路線是在你的類原始int。所以當你沒有明確設置它時,它的實例將具有默認值0,因此當序列化爲json時,它將進入json輸出。

也許你可以對非必填字段使用盒裝整數(Integer),或者使用@JsonIgnoreProperties({"route"}),這樣Jackson就可以忽略它。

+0

我在'@JsonInclude(JsonInclude.Include.NON_NULL)'這行之後試過'@JsonIgnoreProperties({「route」})''SDBeanPost''但我得到這個錯誤'JsonIgnoreProperties無法解析爲類型'。如果路由和方向在請求中有價值,我只想從響應中刪除路由和方向。否則,如果路由爲'0',並且dierection的'「」'也在請求中爲空,我想返回'{「status」:230,「route」:0。 「方向」:「」}'。 –

+0

只需檢查您是否導入了JsonIgnoreProperties。此外,如果你想發送路由時,它設置,使用'Integer'而不是'int'在SDBeanPost路由 – barunsthakur

+0

好的感謝Integer對我來說是更好的選擇。 –