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
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.
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.
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.
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With