jsonasp.net-coresystem.text.json

System.Text.Json - The JSON value could not be converted to System.String


I have the following json being sent to api

{
     "Id":22,
     "UserId":22,
     "Payload":{
        "Field":"some payload value"
        ...more unknown field/values go here
     },
     "ContextTypeId":1,
     "EventTypeId":1,
     "SessionId":1
}

I would like to map it to the following:

  public class CreateTrackItem : IRequest<int>
    {  
        public int Id { get; set; }
        public int UserId { get; set; }

        public string Payload { get; set; }
        public int ContextTypeId { get; set; }
        public int SessionId { get; set; }
        public int EventTypeId { get; set; }
    }

When mapped the Payload property fails that it cannot map json to string, i simply want the Payload to be a string version of the json (will go into a jsonb field in postgres)

I am using .NET Core 3.0 and prefer to use the built in System.Text.Json if possible before switching to Newtonsoft.


Solution

  • You can use Object type instead of string. Or use JToken type from Newtonsoft as Ryan already commented above.

    public object Payload { get; set; }

     public class CreateTrackItem : IRequest<int>
    {  
        public int Id { get; set; }
        public int UserId { get; set; }
    
        public object Payload { get; set; }
        public int ContextTypeId { get; set; }
        public int SessionId { get; set; }
        public int EventTypeId { get; set; }
    }