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

2
  • 1
    Enums are basically fancy integers so getting 0 in your output here is fully expected. Commented Jun 13, 2022 at 8:53
  • Possible this answer is what you need: Serialize enum to string Commented Jun 13, 2022 at 8:58

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.