Search code examples
c#jsonserialization

Enum returned in the web api response is wrapped around extra quotes


I am using the global serializer of System.Text.Json.Serialization like thisoptions.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); in my startup file to have the enum return as string value instead of the index value. And have couple of controller action methods to check how the serilizer is working.

public enum TestEnum
{
    Value1,
    Value111
}

public IActionResult GetEnum()
{
    return Ok(TestEnum.Value1);
}

Now if get the response of the GetEnum() (see below) it gives me the response as ""Value1""

public async Task GETEnumValue()
{
    // my client generation code
    var result = client.SendAsync(request).Result;
    var stringResponse = result.Content.ReadAsStringAsync().Result;        
}

No clue why the extra quotes are being attached here for stringResponse = ""Value1"" If I return a c# model which has this enum as one of the property then I don't see the extra quotes. Any leads here ??


Solution

  • Summary: You serialize your string to JSON, but you never deserialize it.

    This is what happens in detail:

    1. You start with a string Value1.
    2. Then you JSON-encode this string, leading to "Value1" (these double quotes look like C# double quotes, but they are JSON double quotes).
    3. Then you read the result as a string (ReadAsStringAsync) instead of as JSON. Thus, you get a string containing a JSON string literal.

    You can fix this by reading your JSON result as JSON...

    var stringResponse = result.Content.ReadAsJsonAsync<string>().Result;
    

    ...(or by manually deserializing your result.)