Search code examples
c#jsonjson.netjsonconvertjsonconverter

Deserialize json to object in c# does not map values


I'm trying to deserialize a json string by using the Jsonconverter. I have all the values inside the json, I also want to mention that, that specific json is being generated from the swagger, so when i send a payload to the API it maps it into the object model.

However, when i try to deserialize it into the same object, everything is null. What I am doing wrong?

This is how i deserialize it

EmailUrlDto testEmailUrlDto = JsonConvert.DeserializeObject<EmailUrlDto>(jsonString);

JSON format

  {
    "templateUrl": "https://some.blob.url.here.com",
    "paramsHtml": [
  {
    "name": "{{miniAdmin}}",
    "value": "Heyth is Admin!"
  },
  {
   "name": "{{cliBuTree}}",
   "value": "I`m a treeee!"
 }
 ],
 "from": "string",
 "subject": "string",
 "message": "string",
 "isHtmlBody": true,
 "recipients": [
   {
     "recipient": "[email protected]"
   }
 ],
  "cCRecipients": [
    {
      "recipient": "string"
    }
  ],
  "bCCRecipients": [
    {
      "recipient": "string"
    }
  ]
}

EmailUrlDto

public class EmailUrlDto : EmailDto
{
    [Required]
    [JsonPropertyName("templateUrl")]
    public string TemplateUrl { get; set; }

    [Required]
    [JsonPropertyName("paramsHtml")]
    public ParamsHtmlTemplateDto[] ParamsHtml { get; set; }
}

EmailDto

public class EmailDto : Dto
{

    [JsonIgnore]
    public int Id { get; set; }


    [JsonPropertyName("from")]
    [MaxLength(250)]
    public string From { get; set; }


    [JsonPropertyName("subject")]
    [Required]
    [MaxLength(300)]
    public string Subject { get; set; }


    [JsonPropertyName("message")]
    [Required]
    public string Message { get; set; }


    [JsonPropertyName("isHtmlBody")]
    public bool IsHtmlBody { get; set; }


    [JsonIgnore]
    public EStatus EmlStatus { get; set; }


    [JsonPropertyName("smtp")]
    public SMTPConfigurationDto Smtp { get; set; }


    [JsonIgnore]
    public AttachmentDto[] Attachments { get; set; }


    [JsonPropertyName("recipients")]
    public ToRecipientDto[] Recipients { get; set; }


    [JsonPropertyName("cCRecipients")]
    public CcRecipientDto[] CCRecipients { get; set; }


    [JsonPropertyName("bCCRecipients")]
    public BccRecipientDto[] BCCRecipients { get; set; }


    [JsonIgnore]
    public LogDto[] Logs { get; set; }

}

Solution

  • The attributes you are using to name the properties are from System.Text.Json.Serialization namespace (JsonPropertyName for instance) and are used by the System.Web.Script.Serialization.JavaScriptSerializer class during serialization/deserialization.

    You should add also, Newtonsoft's JsonProperty(string) attribute and it should work as expected

    [JsonProperty("from")]
    [JsonPropertyName("from")]
    [MaxLength(250)]
    public string From { get; set; }