How to check if a json key exists?

后端 未结 13 2078
一整个雨季
一整个雨季 2020-11-27 11:38

So, I get some JSON values from the server but I don\'t know if there will be a particular field or not.

So like:

{ \"regatta_name\":\"ProbaRegatta\"         


        
相关标签:
13条回答
  • 2020-11-27 12:19

    you could JSONObject#has, providing the key as input and check if the method returns true or false. You could also

    use optString instead of getString:

    Returns the value mapped by name if it exists, coercing it if necessary. Returns the empty string if no such mapping exists

    0 讨论(0)
  • 2020-11-27 12:22

    Json has a method called containsKey().

    You can use it to check if a certain key is contained in the Json set.

    File jsonInputFile = new File("jsonFile.json"); 
    InputStream is = new FileInputStream(jsonInputFile);
    JsonReader reader = Json.createReader(is);
    JsonObject frameObj = reader.readObject();
    reader.close();
    
    if frameObj.containsKey("person") {
          //Do stuff
    }
    
    0 讨论(0)
  • 2020-11-27 12:22

    You can try this to check wether the key exists or not:

    JSONObject object = new JSONObject(jsonfile);
    if (object.containskey("key")) {
      object.get("key");
      //etc. etc.
    }
    
    0 讨论(0)
  • 2020-11-27 12:23

    I am just adding another thing, In case you just want to check whether anything is created in JSONObject or not you can use length(), because by default when JSONObject is initialized and no key is inserted, it just has empty braces {} and using has(String key) doesn't make any sense.

    So you can directly write if (jsonObject.length() > 0) and do your things.

    Happy learning!

    0 讨论(0)
  • 2020-11-27 12:24

    A better way, instead of using a conditional like:

    if (json.has("club")) {
        String club = json.getString("club"));
     }
    

    is to simply use the existing method optString(), like this:

    String club = json.optString("club);
    

    the optString("key") method will return an empty String if the key does not exist and won't, therefore, throw you an exception.

    0 讨论(0)
  • 2020-11-27 12:25

    JSONObject class has a method named "has":

    http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)

    Returns true if this object has a mapping for name. The mapping may be NULL.

    0 讨论(0)
提交回复
热议问题