1

Im trying to parse in C# using Newtonsoft.Json JSON to anonymous type to use its fields with reflection. But in any ways I get JObject. In runtime it turns out not at all what I need:

enter image description here

What should I use to get anonymous type object from JSON parsing, like when I use dynamic cleanDynamic = new { SomeProperty = "SomeValue" };? Only one similar way I found: JsonConvert.DeserializeAnonymousType(json1, definition), but I can't provide definition, I don't know it! Maybe I have to use another lib? I'm using .net core 2.2.

dbc
  • 104,963
  • 20
  • 228
  • 340
FoxPro
  • 2,054
  • 4
  • 11
  • 34
  • Do you want to deserialize to a **dynamic** type, as in one that implements [`IDynamicMetaObjectProvider`](https://learn.microsoft.com/en-us/dotnet/api/system.dynamic.idynamicmetaobjectprovider?view=netframework-4.7.2), or an [**anonymous** type](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/anonymous-types), a static type that encapsulates a set of read-only properties defined at compile time? Because `JObject` is already a dynamic type, but if you prefer you can deserialize to `ExpandoObject` instead. – dbc Jan 12 '19 at 18:22
  • @dbc yes, i suppose question is not correct, i mean to anonymous type, but without defenetion. I will reformulate. – FoxPro Jan 12 '19 at 18:28
  • 1
    Then this is difficult and doesn't seem to be widely useful. But there's already a basic answer [here](https://stackoverflow.com/a/29428640/344280) to [C# anonymous object with properties from dictionary](https://stackoverflow.com/q/29413942/344280) that does this using `AssemblyBuilder` and `Reflection.Emit`. You would need to modify that code to be recursive. – dbc Jan 12 '19 at 18:37
  • btw i found a video, where DeserializeObject returns anonymous type https://youtu.be/Udg-S-_9t8k?t=114 – FoxPro Jan 12 '19 at 18:41
  • Another option would be to use [tag:f#] and the [JSON Type Provider](http://fsharp.github.io/FSharp.Data/library/JsonProvider.html). Basically it constructs a runtime type by parsing some JSON. See e.g. [FSharp.Data.JsonProvider - Getting json from types](https://stackoverflow.com/q/22280155). You could parse the JSON in an f# project then return it to c# for later use. – dbc Jan 12 '19 at 20:27

0 Answers0