从 JSON 响应中删除密钥

remove a key from the JSON response

我正在使用 Jersey 框架并尝试 return {"status":201} 作为响应,但我现在正在 {"status":201,"route":0}。我需要在另一个响应中 SDBeanPost class 中的路线和方向,但不是在所有响应中。因此,我可以通过添加此行 bean.direction = null; 从响应中删除方向,但我不知道如何在不从 SDBeanPost 中删除 route 的情况下从响应中删除路由?

接收者class

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

}

路线是您 class 中的原始路线 int。因此,当您未明确设置它时,它的实例将具有默认值 0,因此在序列化为 json 时,它会进入 json 输出。

也许您可以对非必填字段使用盒装整数 (Integer) 或使用 @JsonIgnoreProperties({"route"}) 让 Jackson 忽略它。