如何在 dotnet core 中将动态对象序列化为 JSON 字符串? [英] How to serialize a dynamic object to a JSON string in dotnet core?
问题描述
我正在将 JSON 有效负载传递给 API 控制器,其中一个字段是动态的,因为该字段需要作为 JSON 字符串再次传递给另一个 API.dotnet core 3.1 中间层不应该关心打字,因为有效载荷会改变.
I am passing a JSON payload to an API Controller, and one of the fields is dynamic because the field needs to be passed again as a JSON string to another API. The dotnet core 3.1 middle layer shouldn't be concerned with typing, as the payload will change.
这是传入 API 控制器的对象:
This is the object that is passed into the API Controller:
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 中的样子:
Here is a picture of that dynamic
object looks like in VSCode:
当我使用 JsonConvert.SerializeObject(x.Action);
字符串结果没有被正确转换,而是序列化为 ValueKind:"{"ValueKind":1}"
.
When I use JsonConvert.SerializeObject(x.Action);
the string result isn't being properly converted, but instead serializes to ValueKind: "{"ValueKind":1}"
.
我想要的是作为 JSON 字符串的 action 对象值,它应该看起来像 "{"createRepository":{"onboarding":{"service":{"organization":"foo","repositoryName":"foo-2-service","description":"测试服务."}}}}"
What I want to get is the action object value as a JSON string, which should look like "{"createRepository":{"onboarding":{"service":{"organization":"foo","repositoryName":"foo-2-service","description":"A test service."}}}}"
有没有简单的序列化动态对象的解决方案?
Is there a simple solution for serializing a dynamic object?
推荐答案
我遇到了同样的问题,我是这样解决的
I had the same problem and I fixed it this way
using System.Text.Json;
string serializedObject = JsonSerializer.Serialize(x.Action); //Instead of use JsonConvert.SerializeObject(x.Action);
你必须使用 System.Text.Json
而不是 Newtonsoft.Json
.
Instead of Newtonsoft.Json
you have to use System.Text.Json
.
这篇关于如何在 dotnet core 中将动态对象序列化为 JSON 字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!