Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deserializing enums

I have an xml in which one of the elements has an attribute that can be blank. For e.g.,

<tests>
<test language="">
.....
</test>
</tests>

Now, language is enum type in the classes created from the schema. It works fine if the language is specified, it fails to deserialize if it is blank (as shown in example).

Edit: Code for deserialization:

XmlSerializer xmlserializer = new XmlSerializer(type);
StringReader strreader = new StringReader(stringXML);
Object o = serializer.Deserialize(strreader);

How can I handle this scenario

like image 832
genericuser Avatar asked Nov 22 '10 22:11

genericuser


People also ask

How do you deserialize an enum in java?

The @JsonValue annotation is one of the annotations which we can use for both serializing and deserializing enums. Enum values are constants, and due to this, @JsonValue annotation can be used for both. First we simply add the getter method to our Distance. java by using the @JsonValue annotation.

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 serialize an enum 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

You could declare the enum property as nullable:

public Language? Language { get; set; }


EDIT: ok, I just tried, it doesn't work for attributes... Here's another option: don't serialize/deserialize this property directly, but serialize a string property instead :

[XmlIgnore]
public Language Language { get; set; }

[XmlAttribute("Language")]
public string LanguageAsString
{
    get { return Language.ToString(); }
    set
    {
        if (string.IsNullOrEmpty(value))
        {
            Language = default(Language);
        }
        else
        {
            Language = (Language)Enum.Parse(typeof(Language), value);
        }
    }
}
like image 154
Thomas Levesque Avatar answered Oct 28 '22 20:10

Thomas Levesque