gpt4 book ai didi

java - 使用 toJson() 返回 bean 的一部分

转载 作者:行者123 更新时间:2023-11-30 11:03:28 25 4
gpt4 key购买 nike

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

我很感激任何帮助。

接收类:

@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 类:

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

}

最佳答案

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

Annotation used to indicate when value of the annotated property (when used for a field, method or constructor parameter), or all properties of the annotated class, is to be serialized. Without annotation property values are always included, but by using this annotation one can specify simple exclusion rules to reduce amount of properties to write out.

import com.fasterxml.jackson.annotation.JsonInclude;
[...]

@JsonInclude(JsonInclude.Include.NON_NULL)
public class SDBean {

关于java - 使用 toJson() 返回 bean 的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30384861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com