The difference between getString() and optString() in Json

前端 未结 5 800
时光说笑
时光说笑 2020-11-30 22:39

What is the difference between getString() and optString() in JSON?

5条回答
  •  一生所求
    2020-11-30 23:30

    optString() is used to overcome NullPointerException, which we get while using getString() when the required key doesn't exists in json it basically replaces with the default value.

    example let the input Json be

    {
    "name":"abhi",
    "country":"india"
    }
    

    now in java when you execute

    String city = json.getString("city");
    

    it will throw a NullPointerException.

    by using optString(String key, String default) we can overcome the above problem.

    String city= json.optString("city","default");
    
    System.out.println(city);
    

    Output: default

提交回复
热议问题