質問

I am working on an API that accepts XML in the request body.

When I receive the XML, I use the XmlSerializer class to convert the XML to an object. One of the properties of that object is a list of enum values.

What I would like to do is make it so that the client can pass the int value of the enum rather than having to pass in the name of the value.

For example, lets say part of the xml looks like this:

<Amenities>
    <AmenityCode>1</AmenityCode>
    <AmenityCode>2</AmenityCode>
</Amenities>

And I have an my class is defined like this

public class HotelSearch{
  public List<AmenityCode> Amenities { get; set; }
}

public enum AmenityCode {
   AirConditioning = 1,
   AirportTranfer = 2
}

Is there a way to tell the XmlSerializer to accept <AmenityCode>1</AmenityCode> and translate it to AmenityCode.AirConditioning when I serialized a HotelSearch object?

I know I can just create a new HotelSearch object and set all of the properties by parsing through the XML, but my overall goal is laziness and that would defeat the purpose.

役に立ちましたか?

解決

It is recommended to have string values for enums in serialized/deserialized requests. but if you want an int value, then try using the XmlEnum attribute on the enums.

public enum AmenityCode 
{
       [XmlEnum("1")]
       AirConditioning = 1,
       [XmlEnum("2")]
       AirportTranfer = 2
}

there is also a way to create shimmed properties, but that gets too messy when many properties are involved.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top