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

6

21

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:

enter image description here

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?

Within answered 29/2, 2020 at 12:14 Comment(4)
Is this using Newtonsoft.Json, or System.Text.Json?Janettjanetta
ValueKind is from System.Text.Json, but JsonConvert is from Newtonsoft. It's quite possible you can't mix the 2 here. Try using JsonSerializer.Serialize instead of JsonConvert.SerializeObject.Nook
There is a property named ValueKind of JsonElement: JsonElement.ValueKind. So probably your dynamic Action is actually a JsonElement, can you confirm please? A minimal reproducible example showing the JSON and deserialization code would be ideal.Instrumental
The payload coming into the controller is being serialized using System.Text.Json pretty sure. I am not wiring up Newtonsoft in Startup, but I am doing some internal stuff using Newtonsoft else where in the code. And yes, it is a JsonElement. The POCO object I have in the OP might be misleadning.Within
B
34

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.

Balata answered 28/7, 2020 at 19:42 Comment(2)
This doesn't appear to answer the question as System.Text.Json doesn't currently handle dynamic properties.Diacaustic
This worked for me, and I am using dynamic propertiesGob
K
8

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

Kathrinekathryn answered 19/2, 2021 at 10:36 Comment(0)
P
4

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);
Paine answered 1/9, 2022 at 13:0 Comment(0)
T
0

Try this

var jsonString=s.Action.ToString();

This will give you the json string

Traitorous answered 23/4, 2020 at 17:37 Comment(0)
G
0

I had the same issue when parsing a property with the "object" type:

public Dictionary<string, object> Fields { get; set; }

When using Newtonsoft.Json I got a serialised object that contained values looking something like: "Custom.Createdbyuser":{"ValueKind":3}" instead of "Custom.Createdbyuser":"John Doe"

When I switched to System.Text.Json and used the JsonSerializer.Serialze() & JsonSerializer.Deserialize() that fixed the issue for me.

Gaddy answered 19/6 at 10:8 Comment(0)
D
-1

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);
Duong answered 9/8, 2021 at 21:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.