-3

I have a dynamic object that I have to convert to json (anonymous) for passing to an API as param. What is the best way to do this conversion?

There is this post:

How to convert a dynamic object to JSON string c#?

But this does not quite apply to me as I cannot use var as explained in the comment below.

Thanks Anand

Trying to covert

 dynamic d = new ExpandoObject()
 d.prop = "value"

To:

var json = new {prop = "value"}
Anand
  • 1,387
  • 2
  • 26
  • 48
  • Have you tried this? https://stackoverflow.com/questions/38825113/how-to-convert-a-dynamic-object-to-json-string-c – Treasure Dev Jan 13 '20 at 22:55
  • I have seen this post but I don't think it applies to my case. I cannot use var to start with as I have to add properties on the fly after creation. – Anand Jan 13 '20 at 22:58
  • If you need JSON why are you creating a dynamic object? If you have `{"prop" = "value"}` just parse it. – Dour High Arch Jan 13 '20 at 23:06
  • Yes I did it this way: with `param as Dictionary` i serialized `var payloadRequest = JsonConvert.SerializeObject(param); var json = JObject.Parse(payloadRequest);` – Anand Jan 13 '20 at 23:28

1 Answers1

2

If you are in .NET Core You can use System.Text.Json;and serialize as dynamic

public static void Main()
{
    dynamic w = new ExpandoObject() { Date = DateTime.Now, Item1 = 30 };
    w.Item2 = 123;
    Console.WriteLine(JsonSerializer.Serialize<dynamic>(w));
}

class ExpandoObject
{
    public DateTimeOffset Date { get; set; }
    public int Item1 { get; set; }
    public int Item2 { get; set; }
}

fiddle here

But I do not understand why do you need to use dynamic (probably there is some logic behind it)

if you are in .Net Framework you need to use Newtonsoft Json which is basically the same stuff

dynamic results = JsonConvert.SerializeObject<dynamic>(w);
TiGreX
  • 1,602
  • 3
  • 26
  • 41