How to parse json string object in Android

First of all you have understand what is jsonObject and jsonObjectArray.
ex. of jsonObject
{
“Validate”: “true”
}
if string start with “{” then it’s a only a object.
[
{
“Validate”: “true”
}
]
if string start with “[” then its array of object.

Here I describe both how to parse object or array of string as below.
Create a Class it has a one property.

public class Users {
public String Validate;
public void setUser(String Validate)
{
this.Validate = Validate;
}
public String getValidate()
{
return Validate;
}
}

—– bleow function parse json… create a new class which is parse json string
public class jsonParser {
JSONObject jsonObject;
JSONArray jsonArray;
Users objUser;

public jsonParser()
{
objUser = new Users();
}
public Users parseUser(String str)
{
try {
jsonObject = (JSONObject) new JSONObject(str);

objUser.companyId = jsonObject.getString(UserConstant.Company_Id);
objUser.FullName= jsonObject.getString(UserConstant.Full_Name);
objUser.LastLoginDate= jsonObject.getString(UserConstant.Last_Login_Date);
objUser.Password= jsonObject.getString(UserConstant.PASSWORD);
objUser.UserId = jsonObject.getString(UserConstant.User_Id);
objUser.Validate= jsonObject.getString(UserConstant.VALIDATE);
objUser.WrongPassCount= jsonObject.getInt(UserConstant.WRONGPASSCOUNT);
objUser.isActiveDirectory= jsonObject.getBoolean(UserConstant.IsActiveDirectory);

Log.d(“Json Result = ” , objUser.Validate);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
objUser=null;
}

return objUser;
}

public ArrayList parseUsers(String str)
{
ArrayList appUserList= new ArrayList();
Users user;
try {
jsonArray = (JSONArray) new JSONArray(str);
int arrayLength = jsonArray.length();

for(int i=0;i<arrayLength;i++)
{
user = new Users();
JSONObject arrayObject1 = jsonArray.getJSONObject(i);
user.setUser(arrayObject1.getString(UserConstant.Company_Id),
arrayObject1.getString(UserConstant.Full_Name),
arrayObject1.getString(UserConstant.Last_Login_Date),
arrayObject1.getString(UserConstant.PASSWORD),
arrayObject1.getString(UserConstant.User_Id),
arrayObject1.getString(UserConstant.VALIDATE),
arrayObject1.getInt(UserConstant.WRONGPASSCOUNT),
arrayObject1.getBoolean(UserConstant.IsActiveDirectory)
);
appUserList.add(user);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return appUserList;
}
}

Share