Answered by:
How to avoid null value property class property from Json Serialization

Question
-
User-712926555 posted
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 return only message and Status. but it will return all like as follows
{"message":"username or password is invalid","BranchId":0,"BranchName":null,"Id":0,"Name":null,"Password":null,"RoleId":0,"Status":0}
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 service.asmx
[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); }
Saturday, November 4, 2017 5:22 AM
Answers
-
User475983607 posted
Frankly, the design has many issues. I do not recommend returning two different JSON types from a single web method call - that's confusing. Also you should use the framework serializer rather that building your own.
Hhere is an example.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Script.Services; using System.Web.Services; using System.Xml.Serialization; namespace AsmxDemo { /// <summary> /// Summary description for WebService1 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService] public class WebService1 : System.Web.Services.WebService { //Mock data public List<User> Users; public WebService1() { Users = new List<AsmxDemo.User>() { new User() { BranchId = 1, BranchName = "My branch Name", Id=1, message = "valid user", Name = "admin", Password = "admin", RoleId = 1, Status = 1 }, new User() { BranchId = 2, BranchName = "Branch Two", Id=2, message = "valid user", Name = "user", Password = "user", RoleId = 2, Status = 2 }, }; } [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public LoginResult appLogin(String userName, String passWord) { User User = GetAdmin_AppUserBLL(userName); if(User == null) { return new AsmxDemo.LoginResult() { message = "invalid user", Status = 0 }; } return User; } //Mock DB call public User GetAdmin_AppUserBLL(string userName) { return Users.Where(m => m.Name == userName).FirstOrDefault(); } } //Models public class LoginResult { public string message { get; set; } public int Status { get; set; } } public class User : LoginResult { public int BranchId { get; set; } public string BranchName { get; set; } public int Id { get; set; } public string Name { get; set; } public string Password { get; set; } public int RoleId { get; set; } public string message { get; set; } public int Status { get; set; } } }
The client implementation (same domain)
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script> <script> $(function () { $('#GetData').click(function () { //Placeholder for input parameters var data = {}; data.userName = "admin"; data.passWord = "admin"; //Get chart data $.ajax({ url: '/WebService1.asmx/appLogin', type: 'POST', dataType: 'Json', contentType: 'application/json; charset=utf-8', data: JSON.stringify(data) }).done(function (response) { console.log(response); }).fail(function (error) { console.log(error); }); }); }); </script> </head> <body> <input id="GetData" type="button" value="button" /> </body> </html>
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Saturday, November 4, 2017 6:32 PM