【问题标题】:System.Text.Json - The JSON value could not be converted to System.StringSystem.Text.Json - JSON 值无法转换为 System.String
【发布时间】:2020-02-25 03:04:27
【问题描述】:

我有以下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 成为json 的string 版本(将进入jsonb 中的字段postgres)

我正在使用 .NET Core 3.0,如果可能,我更喜欢使用内置的 System.Text.Json,然后再切换到 Newtonsoft。

【问题讨论】:

  • Payload 必须是 class 对象,property Field。 "Payload":{ "Field":"some payload value" },这是一个复杂的对象,不是字符串。
  • @RyanWilson 因为负载结构未知,除了它将是有效的 json 之外,它不可能构造一个类,这就是为什么该属性被设置为一个字符串,它将接受任何 json被扔了
  • 那你要么需要写一个自定义的JSON Converter,要么尝试使用JToken类型,请看这篇文章(stackoverflow.com/questions/29980580/…)

标签: json asp.net-core system.text.json


【解决方案1】:

如果您使用的是 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();

}

【讨论】:

    【解决方案2】:

    您可以使用对象类型而不是字符串。或者使用来自 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; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-14
      • 2021-10-30
      • 1970-01-01
      • 1970-01-01
      • 2015-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多