格式化Web API结果

时间:2017-03-08 14:23:50

标签: .net xml

我在Web APi中收到XML结果:

<ArrayOfResult ....> 
<Result>
 <Id>
 <FirstName></FirstName>
 <LastName></LastName>
 <MiddleName></MiddleName>
 <Address1></Address1>
 <Address2></Address2>
</Result>
</ArrayOfResult>

是否可以将其格式化为:

<Result>
 <WholeName>
       <LastName></LastName>
       <FirstName></FirstName>
       <MiddleName></MiddleName>
 </WholeName>
 <Addresses>
       <Address1></Address1>
       <Address2></Address2>
 </Address>
</Result>

1 个答案:

答案 0 :(得分:2)

您现在有一个结果类:

public class Result
{
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MiddleName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
}

然后从API方法返回一个数组,使其在显示时序列化:

var results = new Result[]
{
    new Result { Id = "123", ... },
};

现在您想要更改此响应的结构。为此,您需要定义一个新类型,以便将数据保存在您想要的结构中:

public class Result
{
    public WholeName WholeName { get; set; }
    public List<Address> WholeName { get; set; }
}

public class WholeName
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MiddleName { get; set; }
}

public class Address
{
    public string Address { get; set; }
}

将结果映射到该类型的实例:

var newResult = new Result
{
    WholeName = new WholeName
    {
        FirstName = oldResult.FirstName,
        ...
    },
    Addresses = new List<Address>
    {
        new Address
        {
            Address = oldResult.Address1,
            ...
        }
    }
}