Home > OS >  How to assign enum values to class object in c#
How to assign enum values to class object in c#

Time:06-13

i have used following enum

public enum Vehicle
{
    [EnumMember(Value = "Use of Carriage")]
    UseofCarriage
}

i want to use that in class object but with following code i am getting that enum value in json as 0 instead i want the value of enummember

public void TestCase1()
    {
        // Arrange
        Vehicle vehicle = new Vehicle();
        vehicle.Vehicle = Vehicle.UseofCarriage;
   
        // Act
        string output = JsonConvert.SerializeObject(vehicle);

        // Assert
        _test.WriteLine(output);
    }

can anybody suggest

CodePudding user response:

You can add [JsonConverter(typeof(StringEnumConverter))] in the class Vehicle. It should produce the result you expect in the test output.

public class Vehicle
{
    [JsonProperty("Vehicle")]
    [JsonConverter(typeof(StringEnumConverter))]
    public Vehicle Vehicle { get; set; }
}

Some documentation about serialisation attributes here in Json.net : https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm

  • Related