0

We are trying to migrate some old .net framework projects to .net 6. The old .net projects use newton Json to deserialize or serialize and we found some behaviour differences in System.Text.Json.

For example, for this object:

{
    "Codes": [
        {
            "Code": "HE37",
            "InstrType": "F",
            "PriceType": 2
        },
        {
            "Code": "M996200",
            "InstrType": "N",
            "FundCiticode": "N2J8"
        }
    ],
    "SeriesTypes": [
        1,
        2
    ],
    "Span": 8,
    "Period": "Weekly",
    "Shortest": "true",
}

Period is an Enum, in newton Json, we can provide either string or value (e.g. 2). Looks like we will need JsonStringEnumConverter to walk around this.

JsonSerializerOptions options = new JsonSerializerOptions
            {
                Converters = {
                    new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)
                }
            };

"Shortest" is a bool, in newton Json, we can provide a string "true" or bool true. In System.Text.Json, it will throw exception if a string "true" is provided.

It will be quite a lot of hassle if we change the behaviour of our system (as various external consumers already send bool value as a string). Is there a way to make System.Text.Json accept string boolean?

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
daxu
  • 3,514
  • 5
  • 38
  • 76

1 Answers1

0

Having

public enum Number
{
    One = 1,
    Two = 2
}

public record O {
    public Number Number {get; set;}
}

and

static O Deserialise(string json)
{
    JsonSerializerOptions options = new JsonSerializerOptions {
        Converters = { new System.Text.Json.Serialization.JsonStringEnumConverter() } 
        };

    var o = JsonSerializer.Deserialize<O>(json, options);
    return o;
}

the following

Console.WriteLine(Deserialise("{ \"Number\": \"One\"}"));
Console.WriteLine(Deserialise("{ \"Number\": 2}"));

prints

O { Number = One }
O { Number = Two }

which shows that both numbers and string values will be handled.

tymtam
  • 31,798
  • 8
  • 86
  • 126