I have a JSON object like
{
    "width": 200,
    "height": 150,
    "objectType": "container"
}
and in C# I have a class like
class MyObject {
    int width;
    int height;
    ObjectType objectType;
}
whereas ObjectType is an enum type:
enum ObjectType {
    container, banner
}
Now I want to deserialize the JSON object and transform the string "container" into the enum value container. For I am quiety new to C# I can't apply solutions to similar questions. I only found questions like "how to serialize a JSON array of enums?"
I think I must somehow apply StringEnumConverter but only to the attribute "objectType"?
I tried like
var settings = new JsonSerializerSettings
{
    Converters = new[] { new StringEnumConverter() }
};
MyObject obj = JsonConvert.DeserializeObject<MyObj>(strJson);
How do I correctly apply the StringEnumConverter to convert the JSON object to the given C# object?
Decorate the Class property using [JsonConverter(typeof(StringEnumConverter))]. This notifies JSON.net to only serialize this property to the enumeration name.
source
Edit your model class:
public enum ObjectType
{
    container,
    banner
}
public class MyObject
{
    public int width;
    public int height;
    [JsonConverter(typeof(StringEnumConverter))]
    public ObjectType objectType;
}
and deserialize
 public void Test()
    {
        var json = "{\"width\": \"200\",\"height\": \"150\",\"objectType\": \"container\"}";
        MyObject obj = JsonConvert.DeserializeObject<MyObject>(json);
    }
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