示例:Mono的DataContractJsonSerializer不会序列化,但.NET会

这是一个准备在Xamarin和VS2013中运行的程序。

我有一个问题,单声道不调用序列化器子类,并需要解决该问题。

我应该如何修改SetMembershipProof,以便它将调用位于嵌套子类中的属性[OnSerializing]的方法?

using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.Text; using System.Threading.Tasks; namespace MonoBug { class Program { static void Main(string[] args) { SetMembershipProof2 setMembershipProof = new SetMembershipProof2(); string setProofJSON = CryptoSerializer.Serialize(setMembershipProof); // Inspect the contents of SetProofJSON, it is null under mono, and not null in .NET } } public class CryptoSerializer { ///  /// Serialize serializable types in namespace UProveCrypto.PolyProof. ///  /// input type /// instance of serializable type /// JSON string public static string Serialize(T obj) { string result; try { using (MemoryStream ms = new MemoryStream()) { DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType()); jsonSerializer.WriteObject(ms, obj); ms.Position = 0; StreamReader reader = new StreamReader(ms); result = reader.ReadToEnd(); } } catch (Exception e) { throw new SerializationException(obj.GetType().Name, e); } return result; } } [DataContract] public abstract class GroupParameterizedSerializer2 { [OnSerializing] public void SerializeGroup(StreamingContext context) { } } [DataContract] public class SetMembershipProof2 : GroupParameterizedSerializer2 { #region Serialization ///  /// Serialization of a ///  [DataMember(Name = "a", EmitDefaultValue = false, Order = 2)] internal string[] _a; ///  /// Serialization of c ///  [DataMember(Name = "c", EmitDefaultValue = false, Order = 3)] internal string[] _c; ///  /// Serialization of r ///  [DataMember(Name = "r", EmitDefaultValue = false, Order = 4)] internal string[] _r; ///  /// Serialize a, c, r. ///  /// The streaming context. [OnSerializing] internal void OnSerializing(StreamingContext context) { Console.WriteLine("Debug: This isn't called in Mono..."); List t = new List(); t.Add("data1"); _a = t.ToArray(); t.Clear(); t.Add("data2"); _c = t.ToArray(); t.Clear(); t.Add("data3"); _r = t.ToArray(); } #endregion } } 

将序列化程序更改为:

 internal string GetJson(T obj) { ... DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType()); ... } 

根据您调用GetJsontypeof(T)可能会返回序列化对象obj的超类。 另一方面, obj.GetType()始终返回正在序列化的对象的特定类。 这可能就是为什么没有在Mono中调用子类的[OnSerializing]方法的原因。