数据契约单值结构

本文关键字:结构 单值 契约 数据 | 更新日期: 2023-09-27 18:14:44

我有一个有点像enum的结构,除了它有一堆方法:

public struct ComponentIdentifier : IComparable
{
    private long identifier;
    ...
}

我希望这个序列化成这样& lt; ComponentIdentifier> 1234 & lt;/ComponentIdentifier>这可能吗?

我想让它为xml和json工作。

谢谢。

数据契约单值结构

有几个选项。

  1. 选项1 -在ComponentIdentifier处理序列化的所有父对象中添加属性
  2. 选项2 -用户数据合同代理
  3. 选项3 -使用JSON。净的JsonConverter

缺点

  1. 选项1 -所有使用ComponentIdentifier &标识符公开
  2. 选项2 - 您将无法使用此方法反序列化
  3. 选项3 -非microsoft库,可能需要性能调优

我自己也在解决这个问题,我倾向于选择#3。我希望微软能做另一个版本的DataContractSerializer,使它更灵活一点。

选项1:

static void Main(string[] args)
{
    var serializeMe = new Foo() { Id = new ComponentIdentifier() };
    var xml = Serialize(serializeMe);
    Console.WriteLine(xml);
    Console.ReadKey();
}
[DataContract]
public class Foo
{
    [DataMember(Name = "Id")]
    private string IdForSerialization
    {
        get { return Id.identifier.ToString(); }
        set { Id = new ComponentIdentifier() {identifier = int.Parse(value)}; }
    }
    public ComponentIdentifier Id { get; set; }
}
[DataContract]
public struct ComponentIdentifier
{
    [DataMember]
    public long identifier;
}
// thanks to http://stackoverflow.com/questions/5010191/using-datacontractserializer-to-serialize-but-cant-deserialize-back
public static string Serialize(object obj)
{        
    using (MemoryStream memoryStream = new MemoryStream())
    using (StreamReader reader = new StreamReader(memoryStream))
    {
        DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
        serializer.WriteObject(memoryStream, obj);
        memoryStream.Position = 0;
        return reader.ReadToEnd();
    }
}

选项2:

static void Main(string[] args)
{
    var serializeMe = new Foo() { Id = new ComponentIdentifier() };
    var xml = Serialize(serializeMe, new ComponentIdentifierSurrogate());
    Console.WriteLine(xml);
    Console.ReadKey();
}
[DataContract]
public class Foo
{
    [DataMember]
    public ComponentIdentifier Id { get; set; }
}
[DataContract]
public struct ComponentIdentifier
{
    [DataMember]
    public long identifier;
}
class ComponentIdentifierSurrogate : IDataContractSurrogate
{
    public Type GetDataContractType(Type type)
    {
        if (type == typeof(ComponentIdentifier))
            return typeof(string);
        return type;
    }
    public object GetObjectToSerialize(object obj, Type targetType)
    {
        if (obj is ComponentIdentifier)
            return ((ComponentIdentifier)obj).identifier.ToString();
        return obj;
    }
    ...
}
public static string Serialize(object obj, IDataContractSurrogate surrogate)
{
    using (MemoryStream memoryStream = new MemoryStream())
    using (StreamReader reader = new StreamReader(memoryStream))
    {
        DataContractSerializer serializer = new DataContractSerializer(obj.GetType(), null, int.MaxValue, false, false, new ComponentIdentifierSurrogate());
        serializer.WriteObject(memoryStream, obj);
        memoryStream.Position = 0;
        return reader.ReadToEnd();
    }
}

选项3:

static void Main(string[] args)
{
    var serializeMe = new Foo() { Id = new ComponentIdentifier() };
    var xml = Serialize(serializeMe);
    Console.WriteLine(xml);
    Console.ReadKey();
}
[DataContract]
public class Foo
{
    [DataMember]
    public ComponentIdentifier Id { get; set; }
}
[DataContract, JsonConverter(typeof(ComponentIdentifierJsonConverter))]
public struct ComponentIdentifier
{
    [DataMember]
    private long identifier;
    public class ComponentIdentifierJsonConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteValue(((ComponentIdentifier)value).identifier.ToString());
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            return new ComponentIdentifier() { identifier = int.Parse((string)JToken.ReadFrom(reader)) };
        }
        public override bool CanConvert(Type objectType)
        {
            if (objectType == typeof(ComponentIdentifier))
                return true;
            return false;
        }
    }
}
public static string Serialize(object obj)
{
    var json = JsonConvert.SerializeObject(obj);
    var xml = JsonConvert.DeserializeXNode(json);
    xml = new XDocument(
        new XDeclaration("1.0", "utf-8", "yes"),
        new XElement(obj.GetType().Name, xml.Root));
    return xml.ToString();
}

祝你好运!