System.Text.Json - The JSON value could not be converted to System.String
17,792
Solution 1
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; }
}
Solution 2
If you are using asp.net core 3.0 then this has built-in JSON support. I have used the following and it works without setting the custom input handler.
//// using System.Text.Json;
[HttpPost]
public async Task<IActionResult> Index([FromBody] JsonElement body)
{
string json = System.Text.Json.JsonSerializer.Serialize(body);
return Ok();
}
Author by
Zoinky
Updated on June 30, 2022Comments
-
Zoinky almost 2 years
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 mapjson
to string, i simply want thePayload
to be astring
version of thejson
(will go into ajsonb
field inpostgres
)I am using .NET Core 3.0 and prefer to use the built in
System.Text.Json
if possible before switching toNewtonsoft
.