[英]JAVA org.json not showing empty value
Here is my JAVA JSON code 这是我的JAVA JSON代码
@GET
@Consumes("application/x-www-form-urlencoded")
@Path("/getAllEmp")
public Response GetAllEmp() {
JSONObject returnJson = new JSONObject();
try {
ArrayList<Emp_Objects> objList = new ArrayList<Emp_Objects>();
DBConnection conn = new DBConnection();
objList = conn.GetEmpDetails();
JSONArray empArray = new JSONArray();
if (!objList.isEmpty()) {
GetLocation loc = new GetLocation();
for (Emp_Objects obj : objList) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", obj.id);
jsonObj.put("name", obj.name);
jsonObj.put("email", obj.email);
jsonObj.put("address", obj.address);
empArray.put(jsonObj);
}
}
returnJson.put("data", empArray);
} catch (Exception e) {
}
return Response.ok(returnJson.toString()).header("Access-Control-Allow-Origin", "*").build();
}
When i execute this it gives me the following json 当我执行它时,它给了我下面的json
{
"data": [{
"id": 1,
"name": "123_name"
}, {
"id": 2,
"name": "321_name",
"email": "xyz@asd.com"
}]
}
In the above json email and address are missing because email and address is null on database . 在上面的json中,由于数据库上的email和address为null,所以缺少email和address 。
So can i show json with empty value like following 所以我可以显示带有空值的json如下
{
"data": [{
"id": 1,
"name": "123_name",
"email": "",
"address": ""
}, {
"id": 2,
"name": "321_name",
"email": "",
"address": ""
}]
}
I am using JAVA and org.json with MySQL database. 我正在将JAVA和org.json与MySQL数据库一起使用。
If the objects are null, insert an empty String instead. 如果对象为空,则插入一个空字符串。
jsonObj.put("email", obj.email == null ? "" : obj.email);
jsonObj.put("address", obj.address == null ? "" : obj.address);
If you have a larger amount of rows to process, I recommend you to turn this is to a function for better readability and to save you some time. 如果要处理的行数量更多,建议您将其转为一个函数,以提高可读性并节省一些时间。
jsonObj.put("email", nullToEmpty(obj.address));
private String nullToEmpty(String arg) {
return arg == null ? "" : arg;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.