这是一个可以在Xamarin和VS2013中运行的程序。
我遇到的问题是mono不会调用序列化程序子类,并且需要解决该问题。
问题
我应该如何修改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<SetMembershipProof2>(setMembershipProof);
// Inspect the contents of SetProofJSON, it is null under mono, and not null in .NET
}
}
public class CryptoSerializer
{
/// <summary>
/// Serialize serializable types in namespace UProveCrypto.PolyProof.
/// </summary>
/// <typeparam name="T">input type</typeparam>
/// <param name="obj">instance of serializable type</param>
/// <returns>JSON string</returns>
public static string Serialize<T>(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
/// <summary>
/// Serialization of a
/// </summary>
[DataMember(Name = "a", EmitDefaultValue = false, Order = 2)]
internal string[] _a;
/// <summary>
/// Serialization of c
/// </summary>
[DataMember(Name = "c", EmitDefaultValue = false, Order = 3)]
internal string[] _c;
/// <summary>
/// Serialization of r
/// </summary>
[DataMember(Name = "r", EmitDefaultValue = false, Order = 4)]
internal string[] _r;
/// <summary>
/// Serialize a, c, r.
/// </summary>
/// <param name="context">The streaming context.</param>
[OnSerializing]
internal void OnSerializing(StreamingContext context)
{
Console.WriteLine("Debug: This isn't called in Mono...");
List<string> t = new List<string>();
t.Add("data1");
_a = t.ToArray();
t.Clear();
t.Add("data2");
_c = t.ToArray();
t.Clear();
t.Add("data3");
_r = t.ToArray();
}
#endregion
}
}
答案 0 :(得分:0)
将序列化程序更改为:
internal string GetJson<T>(T obj)
{
...
DataContractJsonSerializer jsonSerializer =
new DataContractJsonSerializer(obj.GetType());
...
}
根据您调用GetJson<T>
的方式,typeof(T)
可能会返回序列化对象obj
的超类。另一方面,obj.GetType()
始终返回正在序列化的对象的特定类。这可能就是为什么没有在Mono中调用子类的[OnSerializing]
方法。