Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

java - How to test if a JSONObject is null or doesn't exist

I have a set of JSONObject values which i receive from a server and operate on. Most times I get a JSONObject with a value (let's say statistics) and sometimes, it returns an Error object with a code and a description of the error.

How do I structure my code so that it doesn't break if it returns the error. I thought I could do this, but doesn't work.

public void processResult(JSONObject result) {
    try {
        if(result.getJSONObject(ERROR) != null ){
            JSONObject error = result.getJSONObject(ERROR);
            String error_detail = error.getString(DESCRIPTION);
            if(!error_detail.equals(null)) {
                //show error login here
            }
            finish();
        }
        else {
            JSONObject info = result.getJSONObject(STATISTICS);
            String stats = info.getString("production Stats"));
        }
    }
}
question from:https://stackoverflow.com/questions/12585492/how-to-test-if-a-jsonobject-is-null-or-doesnt-exist

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use .has(String) and .isNull(String)

A conservative usage could be;

    if (record.has("my_object_name") && !record.isNull("my_object_name")) {
        // Do something with object.
      }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...