简体   繁体   中英

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.

(application/json or 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:

[
    {
        "ID": 1,
        "ProductTitle": "Product 1",
        "Artist": "Artist 1",
        "EAN_Code": "1234567890123",

but the xml response rearranges the elements alphabetically:

    <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:

This is the default behavior for XML Serialization and there is no settings for it.

For a workaround, you could specify the Order for the Properties.

[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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM