shw shw - 1 year ago 175
C# Question

convert dynamic object to C# object

I’m looking to take a dynamic object from a third party API & convert to my C# object with minimal code.
Sort of like what Dapper does with a SQL statement results to a C# object. Is there a library that would do this?
I can do it manually like below, but it seems like alot of code to write everytime I want to retrieve from this API.

public IEnumerable<Requirement> Get()
dynamic requirementsSelect;
requirementsSelect = _RequirementsRepository.GetRequirements();
IList<Requirement> Requirements = new List<Requirement>();
foreach (var req in requirementsSelect)
Requirement requirement = new Requirement();
requirement.Text = req.Text;
requirement.Number = req.Number;
foreach (var node in req.Phrases)
Requirement reqNode = new Requirement();
reqNode.Text = node.Text;
reqNode.Number = node.Number;
return Requirements;


shw shw
Answer Source

I ended up returning the third party as JSON as follows. In my specific case the JSON wasn't showing the properties. I resolved by changing the dynamic object to IEnumerable and I was then able to specify which properties I wanted to retrieve using .Select.

IEnumerable<dynamic> requirements = _RequirementsRepository.GetRequirements();
        return JsonConvert.SerializeObject(new
            Requirement = requirements.Select(x => x.Text),
            Number = requirements.Select(x => x.Number),


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download