Reputation: 2369
In my Android project, when a user logs in, it connects to our server and delivers JSON data to the client. If incorrect username or password is provided, the server responds with JSON data structured as follows:
{
"d": {
"__type": "FMService.LoginUser:#StarHope.FMS.Web.Pages.Service",
"Error": "wrong",
"Permissions": null,
"UserInfo": null
}
}
However, when the user inputs the correct username and password, the value returned from the "Error" key is null. Is this code the correct way to handle this?
try
{
//when Error is not null
String error = (String) map.get("Error");
}
catch (Exception e)
{
//when Error is null
}
Upvotes: 1
Views: 163
Reputation: 132972
parse your json string as use isNull
to check if jsonobject
content NULL or not before adding value to Map:
JSONObject jobject=new JSONObject("YOUR_JSON_STRING");
if(!jobject.isNull("d")){
JSONObject jobjd=jobject.getJSONObject("d");
String strtype,strError;
if(jobjd.isNull("__type")){
strtype=jobjd.getString("__type");
}
else{
//do some code here
strtype="is null";
}
if(jobjd.isNull("Error")){
strError=jobjd.getString("Error");
}
else{
//do some code here
strError="is null";
}
//.....same code here for Permissions and UserInfo
}
else{
//do some code here
}
Upvotes: 2
Reputation: 25761
You can use getString()
. This method will raise a JSONException
if the mapping is missing.
public String getString (String name)
Added in API level 1 Returns the value mapped by name if it exists, coercing it if necessary.
Throws JSONException if no such mapping exists.
You can also test if the mapping exists or is null using isNull()
Note that the Error
field is inside the d
object, not the root.
Upvotes: 1