I am developing an ASP.NET Core project and I am trying to deserialize JSON data using System.Text.Json
. However, I am getting the following error:
Each parameter in the deserialization constructor on type 'kitaphabitati.webmvc.helpers.viewalerts.models.messagedata' must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the object. Fields are only considered when 'jsonserializeroptions.includefields' is enabled. The match can be case-insensitive
Questions:
MessageData
class not match the JSON data?Here is my MessageData
code:
public class MessageData
{
public string Title { get; set; }
public string Content { get; set; }
public MessageData(Title title, string content)
{
Title = title.ToString().ToLower();
Content = content;
}
}
This is because constructor parameter Title
does not match the type of Title
property and it confuses JSON converter, which tries to instantiate object of your class and looks for best matching constructor.
In order to correct that, you need to define one parameterless constructor:
public MessageData() {}
Alternatively you can define constructor that will match each properties' type and annotate it with JsonConstructor
:
[JsonConstructor]
public MessageData(string title, string content)
{
Title = title;
Content = content;
}