✅ Ways to deserialize Json with dynamic model
I'm currently testing out a new API that I discovered, and I want to explore bunch of API functions and the response data. It would simply take too much time for me to define a Type class as the JSON responses are nested with dozens of arrays and objects, so is there a way for me to dynamically convert response data (HttpResponseMessage) into a C# object?
Simply using <dynamic> wouldn't convert it into a C# object
And I only want to use the optimized native JSON libraries provided in .net 6 and 7, so I wouldn't want to rely on Newton, etc. I'm also aware that there's JSON object to C# class convertor, such as
https://json2csharp.com/
, but I solely want to find a way to dynamically convert without needing C# classes.15 Replies
$jsongen
Instantly parse JSON in any language | quicktype
Whether you're using C#, Swift, TypeScript, Go, C++ or other languages, quicktype generates models and helper code for quickly and safely reading JSON in your apps. Customize online with advanced options, or download a command-line tool.
Convert JSON to C# Classes Online - Json2CSharp Toolkit
Convert any JSON object to C# classes online. Json2CSharp is a free toolkit that will help you generate C# classes on the fly.
Or Edit -> Paste Specjail -> JSON as Classes
Either takes just a second
Or if you just want to explore the API, use a client like Nightingale, Insomnia, or Postman
What is the problem using dynamic?
Low performance, the fact that you're completely discarding the type system, and the inability to reason about it in any possible way
Does it have a
.Name
property? ¯\_(ツ)_/¯
Maybe a .Counts
property that's an int[]
? ¯\_(ツ)_/¯
Does it have any properties whatsoever? ¯\_(ツ)_/¯
Did you even deserialize what you wanted? ¯\_(ツ)_/¯
Can you safely convert it to a list? ¯\_(ツ)_/¯Yeah, I understand that. I suggested that because I think OP is asking for quick dirty ways to inspect the incoming json via some type representation. For serious purpose I would always suggest to go typed object as it's have it's own benifit.
Ok gg
So there’s no dynamic ways to convert into c# object without missing the property data?
And do you have tips for organizing json classrs?
I mean, you can parse to
dynamic
, but there will be no guarantee what properties are availableI have multiple requests in its own folders
Far as organizing goes, just make some
Data/JsonModels
folder and stuff them thereSo within that folder, should I make a folder called modal
Sure, that also works
Is it a common practice?
I mean best practice
Depends what architecture you follow. DDD will have you stuff the models somewhere separate, but something like vertical slice architecture will have you place model classes next to appropriate typed clients
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.