如何在 dotnet core 中将动态对象序列化为 JSON 字符串?

Tod*_*den 9 c# json json.net dotnet-httpclient .net-core

我正在将 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; }
    }
Run Code Online (Sandbox Code Playgroud)

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

在此处输入图片说明

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

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

是否有用于序列化动态对象的简单解决方案?

JPo*_*ata 14

我有同样的问题,我是这样解决的

using System.Text.Json;

string serializedObject = JsonSerializer.Serialize(x.Action); //Instead of use JsonConvert.SerializeObject(x.Action);
Run Code Online (Sandbox Code Playgroud)

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


小智 6

使用Newtonsoft.Json而不是默认System.Text.Json

添加Microsoft.AspNetCore.Mvc.NewtonsoftJson包来自NUGETservices.AddControllers().AddNewtonsoftJson()进入Startup.cs => ConfigureServices()


Kir*_*n B 0

尝试这个

var jsonString=s.Action.ToString();
Run Code Online (Sandbox Code Playgroud)

这将为您提供 json 字符串