Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply StringEnumConverter in C# on single attribute of JSON object

Tags:

json

c#

enums

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?

like image 379
elementzero23 Avatar asked Sep 16 '25 09:09

elementzero23


1 Answers

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);
    }
like image 111
M. Wiśnicki Avatar answered Sep 19 '25 06:09

M. Wiśnicki