1
[DataContract()]
    public class Person
    {
        [DataMember()]
        private string _fname;
        [DataMember()]
        private string _lname;
        [DataMember()]
        public string _nickName;

        public Person(string f, string l)
        {
            _fname = f;
            _lname = l;

            _nickName = _fname + _lname.Substring(0, 1);
        }

        public string FullName()
        {
            return _fname + " " + _lname;
        }
    }

I got this Class, if I write my own methods to serialize/deSerialize I can serialize all the members(private/public). howerver when I use this in .net webservice, only public member get serialize and not the private. What am I doing wrong? searched whole SO cant find the solution. Is there a way to tell webservice to serialize all members (public. private, internal..)

the100rabh
  • 4,077
  • 4
  • 32
  • 40
ahsant
  • 1,003
  • 4
  • 17
  • 25
  • have you tried declaring them [`[serializable]`](http://stackoverflow.com/a/5877839/1324033)? – Sayse Jun 20 '14 at 06:46
  • Yes @Sayse, infact I was using [serializable] initially, and that got the same exact problem. then I follwoed [this](http://stackoverflow.com/questions/4314982/c-sharp-serialize-private-class-member) question, but no luck. – ahsant Jun 20 '14 at 06:49
  • What is the serializer being used? XmlSerializer or DataContractSerializer? I guess the webservice is using the former? In that case can you switch to latter? Latter will handle this with ease (even without all those attributes). – nawfal Jul 10 '14 at 07:29

1 Answers1

0

It sounds like maybe your webservice proxy maybe using the XmlSerializer, instead of the DataContractSerializer. This could sometimes be the case if you are communicating with old asmx wbservices or not .net web services. Try changing your private fields to public properties and see if that works.

[DataMember()]
public string _fname { get; set; }
[DataMember()]
public string _lname { get; set; }
[DataMember()]
public string _nickName { get; set; }

If it works then you are using the XmlSerializer. It can not serialize private fields, but the DatacontractSerializer can.

Mike Hixson
  • 5,071
  • 1
  • 19
  • 24
  • it works if I change it to public properties. but due to some limitation I cant use properties. how can I ask VS to use DataContractSerializer instead of xml one. BTW I am using VS2010 and .net framework of my webservice project is 3.5 – ahsant Jun 20 '14 at 07:10
  • Is your webservice a wcf webservice? Or ASP.NET .asmx kind? – Mike Hixson Jun 20 '14 at 07:13
  • Yep, that's why. You will have to get onto WCF webserivces if you want serailize private members with the DataContractSerializer. check out this relevant article, in particular #4. http://www.topwcftutorials.net/2012/06/wcf-vs-asmx-web-services.html – Mike Hixson Jun 20 '14 at 07:20