如何在dotnet core中将动态对象序列化为JSON字符串? [英] How to serialize a dynamic object to a JSON string in dotnet core?

查看:428
本文介绍了如何在dotnet core中将动态对象序列化为JSON字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将JSON有效负载传递给API控制器,并且其中一个字段是动态的,因为该字段需要作为JSON字符串再次传递给另一个API。 dotnet核心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; }
    }

这里是动态的图片对象在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字符串的操作对象值,它应该类似于 { 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?

推荐答案

我遇到了同样的问题,并使用System.Text.Json以这种方式解决了此问题

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);

您必须使用<$ c来代替 Newtonsoft.Json $ c> System.Text.Json 。

Instead of Newtonsoft.Json you have to use System.Text.Json.

这篇关于如何在dotnet core中将动态对象序列化为JSON字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆