.net core System.text.json Serialize & Deserialize

If the field names in your Model class are not exactly the same as in a JSON string, you will need adding an option to guarantee the behavior is what you want. For example, if you have got the following response text:

{"hello":"world"}

and you have a Model class below:

class SampleModel 
{
   public string Hello { get; set; };
}

You can see the property name in your Model class is "Hello" instead of "hello", the following code won't get an expecting result.

SampleModel s = JsonSerializer.Deserialize<SampleModel>("{\"hello\":\"world\"}");

you will get an object like

{
  "Hello": null 
}

You have to use an option below to get it to work.

SampleModel s = JsonSerializer.Deserialize<SampleModel>("{\"hello\":\"world\"}", new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
            });

on the other hand, you have to use the following code to guarantee the serialize behavior:

SampleModel s = JsonSerializer.Serialize(new SampleModel() {Hello="world"}, new JsonSerializerOptions
            {
                DictionaryKeyPolicy = JsonNamingPolicy.CamelCase
            });

Thus you get {"Hello":"world"} instead of {"hello":"world"}.

System.text.json sucks.

Comments

  1. Markdown is allowed. HTML tags allowed: <strong>, <em>, <blockquote>, <code>, <pre>, <a>.