0

READ BEFORE MARK AS DUPLICATED

The "JavaScriptSerializer - JSON serialization of enum as string" question don't answer my question!

I'm trying to serialize an enum but I want the value of the enum present in its description attribute to be serialized and not its value

Important to note that I don't want to use Newtonsoft

Example

using System.Text.Json;
using System.Text.Json.Serialization;

public class MyClassExample 
{
   [JsonConverter(typeof(JsonStringEnumConverter))]
   public YesOrNo IsShipped { get;set; }
}

public enum YesOrNo  {
    [Description("Y")]
    Yes,
    [Description("N")]
    No
}

And I use like that:

var myJson = JsonSerializer.Serialize(new MyClassExample () { IsShipped = YesOrNo.Y });

The return is:

{ "IsShipped": "Yes" } but I expected { "IsShipped": "Y" }

And the same to

var myObject = JsonSerializer.Deserialize<MyClassExample>("{ ""IsShipped"": ""Y"" }");

How can I use the value o enums attribute to serialize/deserialize?

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Bruno Henri
  • 373
  • 1
  • 3
  • 15
  • 3
    Does this answer your question? [JavaScriptSerializer - JSON serialization of enum as string](https://stackoverflow.com/questions/2441290/javascriptserializer-json-serialization-of-enum-as-string) – Roman Patutin Jan 17 '21 at 18:44
  • No, it doesn't solve. My problem is not being able to serialize to string, it is not being able to serialize and deserialize the value present in the enum attribute – Bruno Henri Jan 17 '21 at 18:47
  • Did you try to create own converter for it instead of `JsonStringEnumConverter`? – Fabio Jan 17 '21 at 19:00
  • @RomanPatutin OP doesn't use `JavaScriptSerializer` – Pavel Anikhouski Jan 17 '21 at 20:24
  • It doesn't look like you want to do what you want. You can not implement deserialization this way, because it goes thru the next code: https://github.com/dotnet/runtime/blob/0e0e852e83d5f30dfeeef7ac4999873ee10f9a4b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/EnumConverter.cs#L61 and you cannot override Enum.TryParse. – Roman Patutin Jan 18 '21 at 20:59

0 Answers0