【发布时间】: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