3

我将以下内容json发送到 api

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

我想将其映射到以下内容:

  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; }
    }

当映射Payload属性失败时,它无法映射json到字符串,我只是希望Payload成为一个string版本json(将进入一个jsonb字段postgres

我正在使用 .NET Core 3.0,System.Text.Json如果可能的话,我更喜欢在切换到Newtonsoft.

4

2 回答 2

6

如果您使用的是 asp.net core 3.0,那么它具有内置的 JSON 支持。我使用了以下内容,它无需设置自定义输入处理程序即可工作。

//// using System.Text.Json;

[HttpPost]
public async Task<IActionResult> Index([FromBody] JsonElement body)
{

    string json = System.Text.Json.JsonSerializer.Serialize(body);
    return Ok();

}
于 2019-11-24T03:28:49.647 回答
0

您可以使用对象类型而不是字符串。或者使用来自 Newtonsoft 的 JToken 类型,正如 Ryan 上面已经评论的那样。

公共对象有效载荷 { 得到;放; }

 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; }
}
于 2019-10-29T21:01:12.690 回答