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