Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I serialize an enum value as an int?

I want to serialize my enum-value as an int, but i only get the name.

Here is my (sample) class and enum:

public class Request {     public RequestType request; }  public enum RequestType {     Booking = 1,     Confirmation = 2,     PreBooking = 4,     PreBookingConfirmation = 5,     BookingStatus = 6 } 

And the code (just to be sure i'm not doing it wrong)

Request req = new Request(); req.request = RequestType.Confirmation; XmlSerializer xml = new XmlSerializer(req.GetType()); StringWriter writer = new StringWriter(); xml.Serialize(writer, req); textBox1.Text = writer.ToString(); 

This answer (to another question) seems to indicate that enums should serialize to ints as default, but it doesn't seem to do that. Here is my output:

<?xml version="1.0" encoding="utf-16"?> <Request xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">   <request>Confirmation</request> </Request> 

I have been able to serialize as the value by putting an "[XmlEnum("X")]" attribute on every value, but this just seems wrong.

like image 606
Espo Avatar asked Feb 03 '09 08:02

Espo


People also ask

How do you serialize an enum?

To serialize an enum constant, ObjectOutputStream writes the value returned by the enum constant's name method. To deserialize an enum constant, ObjectInputStream reads the constant name from the stream; the deserialized constant is then obtained by calling the java.

Can you use enum as int?

By default, the type for enum elements is int. We can set different type by adding a colon like an example below. The different types which can be set are sbyte, byte, short, ushort, uint, ulong, and long.

Can we serialize enums?

Because enums are automatically Serializable (see Javadoc API documentation for Enum), there is no need to explicitly add the "implements Serializable" clause following the enum declaration. Once this is removed, the import statement for the java. io.

Can enum be serialized C#?

In C#, JSON serialization very often needs to deal with enum objects. By default, enums are serialized in their integer form. This often causes a lack of interoperability with consumer applications because they need prior knowledge of what those numbers actually mean.


1 Answers

The easiest way is to use [XmlEnum] attribute like so:

[Serializable] public enum EnumToSerialize {     [XmlEnum("1")]     One = 1,     [XmlEnum("2")]     Two = 2 } 

This will serialize into XML (say that the parent class is CustomClass) like so:

<CustomClass>   <EnumValue>2</EnumValue> </CustomClass> 
like image 155
miha Avatar answered Oct 11 '22 01:10

miha