0

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;
            Requirements.Add(requirement);
            foreach (var node in req.Phrases)
            {
                Requirement reqNode = new Requirement();
                reqNode.Text = node.Text;
                reqNode.Number = node.Number;
                requirement.Nodes.Add(reqNode);
        }
        return Requirements;
    }

Thanks

10
  • @MokhtarAshour I was thinking of Newtonsoft.Json but I want it to be a c# object - not json. thanks Commented Aug 7, 2016 at 10:56
  • 1
    @gypsyCoder sure, but I meant to send the JSON from the 3rd party API and deserialise it to a c# object you have in your code Commented Aug 7, 2016 at 11:00
  • @MokhtarAshour thank you. I will look into that now Commented Aug 7, 2016 at 11:02
  • @MokhtarAshour When I convert it to JSON - only one property is coming up. How can I specify what properties should be part of this dynamic object. I convert like this - string jsonString = JsonConvert.SerializeObject(requirements); and it's coming up like this in my browser- [{\"$id\":\"1\"},{\"$id\":\"2\"},{\"$id\":\"3\"}. Thanks Commented Aug 7, 2016 at 13:57
  • by default serialization is done to all properties (I assume it's .NET here). BTW what's $id ? Commented Aug 7, 2016 at 14:41

1 Answer 1

1

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),
        });

Thanks!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.