Reputation: 65
I am creating a webservice using asp.net 4.0.
I have created a asmx file and creating a User.cs Class. It has 8 Properties. I have return a service with json format. If the userlogin is true i need to return all the properties of user.cs, if it's fail i need to return only 2 property.
How to achieve it.
User login is true. It will return all
{"message":"valid user","BranchId":1,"BranchName":"My branch Name","Id":1,"Name":"admin","Password":"admin","RoleId":1,"Status":1}
User login is failed i need to retun only message and Status. but it will return all like as foloows
{"message":"username or password is invalid","BranchId":0,"BranchName":null,"Id":0,"Name":null,"Password":null,"RoleId":0,"Status":0}
I have google it and get the following Link. How to use it based on my login status condition.
If i have used [ScriptIgnore] in my property it will ignore property both case. I need to ignore property when login failed.
My properties like this
// Properties
public int BranchId
{
get { return _BranchId; }
set { if (_BranchId != value) { _BranchId = value; } }
}
public string BranchName
{
get { return _BranchName; }
set { _BranchName = value; }
}
private String _message;
public String message
{
get { return _message; }
set { _message = value; }
}
My webservice
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void appLogin(String userName, String passWord)
{
Admin_AppUserBLL objusr = Admin_AppUserBLL.GetAdmin_AppUserBLL(userName);
string strResponse = "";
if (objusr != null)
{
if (objusr.Password == passWord)
{
objusr.message = "valid username";
strResponse = new JavaScriptSerializer().Serialize(objusr);
}
}
else
{
objusr = new Admin_AppUserBLL();
objusr.message = "username or password is invalid";
strResponse = new JavaScriptSerializer().Serialize(objusr);
}
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.AddHeader("content-length", strResponse.Length.ToString());
Context.Response.Flush();
Context.Response.Write(strResponse);
}
Upvotes: 1
Views: 1670
Reputation: 65
Add reference in Newtonsoft
using Newtonsoft.Json;
while serialize the object
string strResponse = JsonConvert.SerializeObject(objusr, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
it will avoid null value property
Upvotes: 0
Reputation: 331
Add following attribute on your property and also make it nullable by using "?"
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "BranchId")]
public int? BranchId{ get; set; }
It will ignore if value will be null and also json does not contain these peoperties.
Upvotes: 1