【问题标题】:How to serialize a dynamic object to a JSON string in dotnet core?如何将动态对象序列化为 dotnet core 中的 JSON 字符串?
【发布时间】:2020-02-29 12:14:15
【问题描述】:

我将 JSON 有效负载传递给 API 控制器,其中一个字段是动态的,因为该字段需要作为 JSON 字符串再次传递给另一个 API。 dotnet core 3.1 中间层不应该关心打字,因为负载会改变。

这是传递给 API 控制器的对象:

    public class GitHubAction
    {
        [JsonProperty("Title")]
        public string Title { get; set; }

        [JsonProperty("Enabled")]
        [JsonConverter(typeof(BooleanParseStringConverter))]
        public bool Enabled { get; set; }

        [JsonProperty("Action")]
        [JsonConverter(typeof(ExpandoObjectConverter))]
        public dynamic Action { get; set; }
    }

这是dynamic 对象在 VSCode 中的图片:

当我使用 JsonConvert.SerializeObject(x.Action); 时,字符串结果没有被正确转换,而是序列化为 ValueKind:"{\"ValueKind\":1}"

我想要得到的是 JSON 字符串形式的动作对象值,它应该看起来像 "{"createRepository":{"onboarding":{"service":{"organization":"foo","repositoryName":"foo-2-service","description":"A test service."}}}}"

序列化动态对象有简单的解决方案吗?

【问题讨论】:

  • 这是使用Newtonsoft.Json,还是System.Text.Json
  • ValueKind 来自 System.Text.Json,但 JsonConvert 来自 Newtonsoft。很可能你不能在这里混合 2。尝试使用JsonSerializer.Serialize 而不是JsonConvert.SerializeObject
  • JsonElement 中有一个名为ValueKind 的属性:JsonElement.ValueKind。所以可能你的dynamic Action实际上是JsonElement,你能确认一下吗?显示 JSON 和反序列化代码的 minimal reproducible example 将是理想的。
  • 进入控制器的有效载荷正在使用System.Text.Json 进行序列化,非常确定。我没有在 Startup 中连接 Newtonsoft,但我在代码中的其他地方使用 Newtonsoft 做一些内部工作。是的,它是一个 JsonElement。我在 OP 中拥有的 POCO 对象可能具有误导性。

标签: c# json .net-core json.net dotnet-httpclient


【解决方案1】:

我遇到了同样的问题,我用这种方式解决了它

using System.Text.Json;

string serializedObject = JsonSerializer.Serialize(x.Action); //Instead of use JsonConvert.SerializeObject(x.Action);

您必须使用System.Text.Json,而不是Newtonsoft.Json

【讨论】:

  • 这似乎无法回答问题,因为 System.Text.Json 目前不处理动态属性。
【解决方案2】:

使用 Newtonsoft.Json 代替默认的 System.Text.Json

从 nuget 添加 Microsoft.AspNetCore.Mvc.NewtonsoftJson 包和 在 Startup.cs/ConfigureServices() 中的 services.AddControllers().AddNewtonsoftJson()

【讨论】:

    【解决方案3】:

    试试这个

    var jsonString=s.Action.ToString();
    

    这将为您提供 json 字符串

    【讨论】:

      【解决方案4】:

      如果您想使用 Newtonsoft.Json,请按照以下说明操作:

      在使用部分使用这个:

      using Newtonsoft.Json;
      

      然后

      string serializedObject = JsonConvert.SerializeObject(value);
      

      以及反序列化使用:

      var desrializedObject = JsonConvert.DeserializeObject<T>(serializedObject);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-31
        • 2019-02-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多