0

I want to serialize and deserialize a custom class so that it behaves like a simple enum.

For example:

public enum Channel
{
   EMail,
   Telephone
}

Gives the following Json-Representation:

{
    "Channel": "EMail"
}

My current approach:

[Serializable]
public sealed class Channel : ISerializable
{
    public static readonly Channel Email = new Channel("Email");
    public static readonly Channel Telephone = new Channel("Telephone");

    public string Key { get; private set; }

    //// Deserialization
    private Channel(SerializationInfo info, StreamingContext context)
    {
        Key = (string)info.GetValue(nameof(Channel), typeof(string));
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue(nameof(Channel), Key);
    }
}

But this brings up the following json-representation:

{
  "Channel":{"Channel":"Email"}
}

So I want to get rid of the "complex structure" of the class. In the context of serialization it should behave like an enum or string. How can I achieve that behavior? All in all I want to get rid of the encapsulation in the json-representation.

Link
  • 1,307
  • 1
  • 11
  • 23
  • 1
    Did not understand your intentions. Do you want to get rid of the encapsulating "Channel" json node and leave only "Channell" : "Email"? – Avi Meltser May 11 '19 at 18:51
  • 1
    Rather than using `ISerializable`, use a `TypeConverter` or a `JsonConverter`. See [Json.Net: Serialize/Deserialize property as a value, not as an object](https://stackoverflow.com/q/40480489). – dbc May 11 '19 at 19:15

0 Answers0