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?
Newtonsoft.Json
, orSystem.Text.Json
? – JanettjanettaValueKind
is from System.Text.Json, butJsonConvert
is from Newtonsoft. It's quite possible you can't mix the 2 here. Try usingJsonSerializer.Serialize
instead ofJsonConvert.SerializeObject
. – NookValueKind
ofJsonElement
:JsonElement.ValueKind
. So probably yourdynamic Action
is actually aJsonElement
, can you confirm please? A minimal reproducible example showing the JSON and deserialization code would be ideal. – InstrumentalSystem.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