[英]http response - specifying order of xml elements
I have a simple Web API which will return either json or xml, depending on the accept header in the request. 我有一个简单的Web API,它将根据请求中的accept标头返回json或xml。
(application/json or application/xml) (application / json或application / xml)
Here's a snippet of the data class I'm returning: 这是我要返回的数据类的片段:
public int ID { get; set; }
public string ProductTitle { get; set; }
public string Artist { get; set; }
public string EAN_Code { get; set; }
For the json response the name/value pairs are returned in the same order they are declared in the class: 对于json响应,名称/值对以它们在类中声明的相同顺序返回:
[
{
"ID": 1,
"ProductTitle": "Product 1",
"Artist": "Artist 1",
"EAN_Code": "1234567890123",
but the xml response rearranges the elements alphabetically: 但是xml响应按字母顺序重新排列元素:
<Artist>Artist 1</Artist>
<EAN_Code>1234567890123</EAN_Code>
<ID>1</ID>
<ProductTitle>Product 1</ProductTitle>
Is there some property/configuration I can set, to stop the elements being rearranged? 我可以设置一些属性/配置来停止元素的重新排列吗?
Currently I just have: 目前我只有:
services.AddMvc()
.AddMvcOptions(o => o.OutputFormatters.Add(
new XmlDataContractSerializerOutputFormatter()))
.AddJsonOptions(o =>
{
if (o.SerializerSettings.ContractResolver != null)
{
var castedResolver = o.SerializerSettings.ContractResolver
as DefaultContractResolver;
castedResolver.NamingStrategy = null;
}
})
but the xml response rearranges the elements alphabetically:
但是xml响应按字母顺序重新排列元素:
This is the default behavior for XML Serialization and there is no settings for it. 这是XML序列化的默认行为,并且没有设置。
For a workaround, you could specify the Order
for the Properties. 要解决此问题,可以为属性指定
Order
。
[DataContract]
public class JsonXML
{
[DataMember(Order =1)]
public int ID { get; set; }
[DataMember(Order = 2)]
public string ProductTitle { get; set; }
[DataMember(Order = 3)]
public string Artist { get; set; }
[DataMember(Order = 4)]
public string EAN_Code { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.