1

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.

1 Answer 1

4

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

by using your code i have to check all values and write it with all json field, is that possible if i can use any json property if possible?
Updated my answer :) does it answer your question?
@namsu i think you check only null value, so can you check null or empty both?
If an empty String is given as a parameter to that function, it will just return the empty String as is.
@namsu can we have annotation like "@JsonInclude(Include.NULL)" in org.json?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.