开发者

How to convert Json object to cutom class object in web service?

I've scenario where I want to insert data into database without post back. there are around 12 to 13 fields which i need to insert. I'm passing DTO from the client side which is actually Json object. Now the problem which i'm facing is how to convert that Json object which i got in webservice to the "class" (in my case class name is User) object.

<script type="text/javascript" language="javascript">

  $('#<%= btnSaveInfo.ClientID %>').click(function()
  {
        // Initialize the object, before adding data to it.
        //  { } is declarative shorthand for new Object().
        var User = { };
        User.FirstName = $('#<%= txtFirstName.ClientID%>').val();
        User.MiddleName = $('#<%= txtMiddleName.ClientID%>').val();
        User.LastName =  $('#<%=txtLastName.ClientID %>').val();
        User.Gender =  $('table#<%= rdbGenderType.ClientID %> input:radio:checked').val();
        User.DateCreated = Date.UTC();
        User.Description = $('#<%= txtDescription.ClientID%>').val();
        User.DOB = $('#<%= txtDOB.ClientID %>').v开发者_如何学Cal();
        User.Location=$('#<%= txtLocation.ClientID %>').val();
        var DTO = {'User' : User};
        var path = 'MyWebService.asmx/AddNewUser';
        $.ajax
        ({
            type: "POST",
            url: path,               
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: JSON.stringify(DTO),
            async:false,
            success: function(msg)
            {                       

            }   
        }); 
   });

as you can see i'm passing the data as data: JSON.stringify(DTO),. Now how do I convert this JSon object into

   [WebMethod]
   [System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
   public bool AddNewUser(Object User)
   {
       return UserRepository.AddNewUser(User);
   }

In the above case AddNewUser method takes the object of User class. But i'm getting casting error. So how do I convert Json object to the "User" class object?


Why can't you modify AddNewUser method to accept the needed type. For example,

public bool AddNewUser(User user)

Should work as log as User type has default public constructor and property names used from java-script are same as type's property names.


Define your User class like this:

public class User
{
    public User() { }

    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public bool Gender { get; set; }

    public DateTime DateCreated { get; set; }

    public string Description { get; set; }
    public string DOB { get; set; }
    public string Location { get; set; }

}

And edit the signature of the webservice...

 [WebMethod] 
 [System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)] 
 public bool AddNewUser(User user) 
 { 


Your web service should accept a User object, not a Object err, object. =)

public bool AddNewUser(User user)

And it goes without saying your JSON object needs to match the properties of your CLR object. (string to string, bool to bool, etc).

This is why it is good to try and not "coerce" JSON into a Business Object. Use DataContracts to map the JSON to a DataContract object, then map this over to your Business Object. Much safer than trying to go straight from JSON to the Business Object.

Give that a go.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜