0

I'd like to serialize (in JSON format) a list of object where each object has a property of another type of object. This is what I've got so far:

[DataContract]
public class Person{

   [DataMember]
   public string Name { get; set; }
   [DataMember]
   public Address FullAddress { get; set; }
}

[DataContract]
public class Address {
   private readonly byte[] _foo;
   private ulong _value;

   public byte[] Foo { get { return (byte[]) _foo.Clone(); }}

   public ulong Value { get { return _value; } set { return _value; }}

   public Address(byte [] bytes){
      _foo = new byte[bytes.Length];
      Array.Copy(bytes, _foo, bytes.Length);

      foreach(byte b in _foo){
        _value |= b; // I do some bit manipulation here and modify the _value
      }

   }

   public MacAddress() // added this otherwise I get an exception
   {

   }
}

this is how I'm serializing and deserializing:

public class MyJson{

    public MyJson(){
      var list = new List<Person>{ /* added a bunch of person here */ };
      var serializer = new JavaScriptSerializer();
      string json = serializer.Serialize(list);
      // serialization works fine


      var desList = serializer.Deserialize<IList<Person>>(json);

      // the deserialization doesn't properly deserialize Address property.

   }
}

As commented above, the serialization works fine but deserialization doesn't deserialize Address properly. I get a number for Value property (as expected) but not for Foo (I know it is missing a setter but what if, for some reason, I cannot put a setter?).

What am I missing here?

0

1 Answer 1

2

I don't use JSon but if it works like XML serialization I'm guessing it has to do with the fact that Foo doesn't have a setter. You may need to create a custom serialization class that uses the constructor to set Foo. Others may be able to provide more specifics.

Sign up to request clarification or add additional context in comments.

1 Comment

You are right, having a setter for Foo does work. But I'm wondering if there is any other way to make it work in the case of absence of a setter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.