user3441151
user3441151

Reputation: 1910

JAVA org.json not showing empty value

Here is my JAVA JSON code

@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

{
    "data": [{
        "id": 1,
        "name": "123_name"
    }, {
        "id": 2,
        "name": "321_name",
        "email": "[email protected]"
    }]
}

In the above json email and address are missing because email and address is null on database.

So can i show json with empty value like following

{
    "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.

Upvotes: 1

Views: 1061

Answers (1)

numsu
numsu

Reputation: 480

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

Upvotes: 4

Related Questions