数据契约序列化复杂类型 [英] Data contract serialization with complex types

查看:130
本文介绍了数据契约序列化复杂类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的数据协定序列化到XML序列化以下类:

I am using Data Contract serialization to serialize the following classes in XML:

[DataContract]
public partial class Foo
{
    [DataMember]
    public string MyString { get; set; }
    [DataMember]
    public int MyInt { get; set; }
    [DataMember]
    public Bar MyBar { get; set; }
}

[DataContract]
public class Bar
{
    public int BarId { get; set; }
    [DataMember]
    public string BarField { get; set; }
}

当我它会产生这样的XML序列化:

When I serialize it it generates XML like this:

<Foo>
    <MyString>My text</MyString>
    <MyInt>2</MyInt>
    <MyBar>
        <BarField>My bar field</BarField>
    </MyBar>
</Foo>

我想这样做是有 MyBar 字段不会出现是一个复杂的类型,但像这样:

What I would like to do is have the MyBar field not appear as a complex type, but like this instead:

<Foo>
    <MyString>My text</MyString>
    <MyInt>2</MyInt>
    <MyBar>My bar field</MyBar>
</Foo>

我是新来的数据契约序列化,并没有发现任何形式的辅导,解决我的问题。我甚至不知道是否有可能或没有,但我想我会问之前,我放弃了,处理这事情是这样的,或找到一个更好的解决方案。

I'm new to data contract serialization and haven't found any kind of tutorials that address my issue. I don't even know if it is possible or not but I figured I'd ask before I gave up and dealt with it the way it is or found a better solution.

推荐答案

通过修饰数据类为 DataContract ,你是天生的设置结构(XML,JSON等),其该数据将被重新psented当它被序列$ P $

By decorating data classes as DataContract, you are inherently setting the structure (Xml, Json etc) that the data will be represented as when it is serialized.

我可以建议你拆分业务实体和序列化实体'出你的数据类,如关注的问题如果 + 酒吧是你的数据存储或ORM重新presentations,然后删除 [DataContract] - 从他们的:

Can I suggest that you split the concerns of 'Business Entity' and 'Serialization Entity' out of your data classes, e.g. if Foo + Bar are your in memory or ORM representations of the data, then remove the [DataContract]s from them:

public partial class Foo
{
    public string MyString { get; set; }
    public int MyInt { get; set; }
    public Bar MyBar { get; set; }
}

public class Bar
{
    public string BarField { get; set; }
}

于是,专门为序列化格式,再配以 DataContract

[DataContract]
public partial class SerializableFoo
{
    [DataMember]
    public string MyString { get; set; }
    [DataMember]
    public int MyInt { get; set; }
    [DataMember]
    public string MyBar { get; set; }
}

,然后提供的映射功能,从一个到另一个地图。 LINQ是真棒对于这样的工作,如果类具有大致相同属性名称,然后AutoMapper能为你做了很多的工作。

And then provide a mapping function to map from the one to the other. LINQ is awesome for this kind of work, and if the classes have mostly the same property names, then AutoMapper can do a lot of the work for you

例如。

var wireFoo = new SerializableFoo()
{
    MyString = foo.MyString,
    MyInt = foo.MyInt,
    MyBar = foo.Bar.BarField // Do the projection / flattening here
}
// Serialize wireFoo here, or return it from a WCF Service, etc.

这篇关于数据契约序列化复杂类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆