1

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

varun
  • 73
  • 7
  • 1
    Enums are basically fancy integers so getting 0 in your output here is fully expected. – DavidG Jun 13 '22 at 08:53
  • Possible this answer is what you need: [Serialize enum to string](https://stackoverflow.com/a/9159750/8017690) – Yong Shun Jun 13 '22 at 08:58

1 Answers1

3

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

Quentin Roger
  • 6,410
  • 2
  • 23
  • 36