Search code examples
c#serializationjson.net

JsonConvert.SerializeObject is changing a property value from a letter (char) to a number (int)


JsonConvert.SerializeObject is changing a property value from letters to a number. I say 'letters' and 'number' as its a dynamic source object, both before and after are strings but the value 'D' in the source dynamic object is coming out as '1' after serializing to JSON.

SourceObject

public class Response
{
    public dynamic DataBlocks { get; set; }
}

Response.DataBlocks.dynamic.dynamic.PropertyInQuestion == "D"

Serialization Code

var serializedResponse = JsonConvert.SerializeObject(response);

Results in serializedResponse.dynamic.dynamic.PropertyInQuestion == "1"

The result is different depending on which character is in the source property, and its always consistent;

  • C -> 0
  • D -> 1
  • G -> 5
  • M -> 4
  • PC -> 2
  • PD -> 3
  • PM -> 6

This is the data being sent through SerializeObject:

 public enum PropertyInQuestionType {
    C,
    D,
    PC,
    PD,
    M,
    G,
    PM,
    PG,
    U,
    KP,
}

Solution

  • The response you are getting is most likely setting the PropertyInQuestion to an Enum

    JsonConvert.SerializeObject serializes Enum as int.
    And because the property is dynamic when deserializing you get back an int.

    You can, however, use Newtonsoft.Json.Converters.StringEnumConverter and it will serialize it as string.

    This also mean that when deserializing you will get a string (not an enum).

    var serializedResponse = JsonConvert.SerializeObject(response, new StringEnumConverter());