首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用toJson()只返回bean的一部分

使用toJson()只返回bean的一部分
EN

Stack Overflow用户
提问于 2015-05-21 21:41:31
回答 1查看 50关注 0票数 2

我试图返回{"status": its value}‘在routeD!=0的情况下,目前我得到的是{"status":201,"routes":null},我会得到这个形式的响应,{"status":201}没有"routes":null,同时我不想失去routeD==0的响应,例如{"status":230,"routes":[1,9,3]}

我指定任何帮助。

接收类:

代码语言:javascript
复制
@Path("/data")
public class Receiver {

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response storeData(Data data) {
        Database db = new Database();

        String macD = data.getMac();
        int routeD = data.getRoute();
        double latD = data.getLatitude();
        double longD = data.getLongitude();
        double speedD = data.getSpeed();

        // Jackson class to wrapper the data in JSON string.
        SDBean bean = new SDBean();
        if (routeD != 0) {
            bean.status = db.insertData(macD, routeD, latD, longD);         
            return Response.status(bean.status).entity(bean.toJson()).build();

        } else {
            bean.routes = db.detectRoute(latD, longD);
            return Response.status(230).entity(bean.toJson()).build();

        }

    }

}

SDBean类:

代码语言:javascript
复制
public class SDBean {

    public int status;
    public ArrayList<Integer> routes;

    public SDBean(){
    status = 230;
}

    public String toJson() {

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

        }
         System.out.println(json);
        return json;
    }

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-21 23:48:17

只需使用@JsonInclude(JsonInclude.Include.NON_NULL)

注释用于指示注释属性的值(当用于字段、方法或构造函数参数时)或注释类的所有属性何时被序列化。在没有注释的情况下,属性值总是包括在内,但是通过使用该注释,可以指定简单的排除规则,以减少要写入的属性的数量。

代码语言:javascript
复制
import com.fasterxml.jackson.annotation.JsonInclude;
[...]

@JsonInclude(JsonInclude.Include.NON_NULL)
public class SDBean {
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30384861

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档