How to remove root element of list when serializing with DataContracts

主宰稳场 提交于 2019-12-24 04:07:05

问题


I have this class

[DataContract]
public class InsertLoansResponse
{
    private ProcSummary _processingSummary;
    private List<InsertLoanResponse> _items;

    [DataMember]
    public List<InsertLoanResponse> InsertLoanResponses
    {
        get { return _items ?? (_items = new List<InsertLoanResponse>()); }
        set { _items = value; }
    }

    [DataMember]
    public ProcSummary ProcessingSummary
    {
        get { return _processingSummary ?? (_processingSummary = new ProcSummary()); }
        set { _processingSummary = value; }
    }

    public void Add(InsertLoanResponse localState)
    {
        InsertLoanResponses.Add(localState);
    }

    [DataContract]
    public class ProcSummary
    {
        [DataMember(Name = "Success")]
        public int SuccessCount { get; set; }

        [DataMember(Name = "Failure")]
        public int FailureCount { get; set; }
    }
}

It's the response type for a method in my service.

I end up with xml that looks like this:

<InsertLoansResponse>
    <InsertLoanResponses>
        <InsertLoanResponse>
        </InsertLoanResponse>
        <InsertLoanResponse>
        </InsertLoanResponse>
    </InsertLoanResponses>
    <ProcessingSummary>
        <Failure></Failure>
        <Success></Success>
    </ProcessingSummary>
<InsertLoansResponse>

But I do not want the plural InsertLoanResponses root node, I want it to look like this:

<InsertLoansResponse>
    <InsertLoanResponse>
    </InsertLoanResponse>
    <InsertLoanResponse>
    </InsertLoanResponse>
    <ProcessingSummary>
        <Failure></Failure>
        <Success></Success>
    </ProcessingSummary>
<InsertLoansResponse>

回答1:


Perhaps change your class rather than your serializer.

[DataContract]
public class InsertLoansResponse : List<InsertLoanResponse>
{
   private ProcSummary _processingSummary;
   private List<InsertLoanResponse> _items;

   // and remove the Add method, as this is now implicit to the class
}

This way you will not get a nested property when serializing.




回答2:


You'll probably need to define a custom MessageContract for this operation. Check out the following link, specifically the section on "Using Arrays Inside Message Contracts" and the MessageHeaderArrayAttribute.

http://msdn.microsoft.com/en-us/library/ms730255.aspx



来源:https://stackoverflow.com/questions/17681057/how-to-remove-root-element-of-list-when-serializing-with-datacontracts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!