简体   繁体   中英

How to serialize a dynamic object to a JSON string in dotnet core?

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.

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

Here is a picture of that dynamic object looks like in VSCode:

在此处输入图像描述

When I use JsonConvert.SerializeObject(x.Action); the string result isn't being properly converted, but instead serializes to ValueKind: "{\"ValueKind\":1}" .

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

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

Use Newtonsoft.Json instead of default System.Text.Json

Add Microsoft.AspNetCore.Mvc.NewtonsoftJson package from nuget and services.AddControllers().AddNewtonsoftJson() in Startup.cs/ConfigureServices()

Try this

var jsonString=s.Action.ToString();

This will give you the json string

If you want to use Newtonsoft.Json then follow this instructions :

in using section use this :

using Newtonsoft.Json;

Then

string serializedObject = JsonConvert.SerializeObject(value);

and for Deserializing use :

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

You can use Newtonsoft.Json.Converters.ExpandoObjectConverter to help you with this.

dynamic action = new ExpandoObject();
action.YourProperty = new ...;
var converter = new ExpandoObjectConverter();
var jsonString = JsonConvert.SerializeObject(action, converter);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM