1

I want to serialize enum as string using JSON.NET but I want Enum value to serialize without string quotes

    [JsonConverter(typeof(StringEnumConverter))]
    enum Gender { Male, Female }

    class Test
    {
        public Gender { get; set; }
    }

Right now I'm getting output as { "Gender": "Male" }

{ "Gender": Male }  //Male is without quotes
4
  • 6
    Why would you want this? Strings have to have quotes in JSON. Commented Jul 19, 2019 at 8:29
  • This seems like XY problem Commented Jul 19, 2019 at 8:32
  • What are you trying to do? Are you assuming there's going to be a javascript variable with the same name, or...? JSON doesn't have an enum type, so you have to choose between string and number - and strings need to be quoted. Commented Jul 19, 2019 at 8:35
  • I know why you want this, because I got into a similar situation. You may want the string version of the enum to use internally. Do it like this JsonConvert.SerializeObject(yourEnum).Replace("\"", "") Commented Sep 8, 2023 at 16:43

2 Answers 2

2

It is not possible because that json will be invalid. You can check how valid json looks like on https://jsonlint.com.

All JSON Convert libraries are following valid json structure, you can always write your own json converter to do that, but I wouldn't recommend that at all.

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

Comments

0

This is not possible (and really not recommended) because it does not respect JSON syntax.

See : [https://www.w3schools.com/js/js_json_syntax.asp][1]

In JSON, values must be one of the following data types:

a string a number an object (JSON object) an array a boolean null

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.