0

I'm trying to convert a nested Dictionary to nested class base on its type. For example. I have this dictionary:

{
    "owner": {
        "name": {
            "first": "Linh",
            "last": "Nguyen"
        },
        "age": "Nguyen"
    },
    "power": {
        "index": "1",
        "range": "5"
    }
}

And I have this nested class :

    public class AccountRegistrationViewModel
    {
        /// <summary>
        /// Account owner.
        /// </summary>
        [Required]
        public Owner Owner { get; set; }

        /// <summary>
        /// User age.
        /// </summary>
        [Required]
        public int Age { get; set; }

        /// <summary>
        /// Account photo.
        /// </summary>
        [Required]
        public List<HttpFile> Photos { get; set; }
    }

    public class Owner
    {
        public Name Name { get; set; }
    }

    public class Name
    {
        public string First { get; set; }

        public string Last { get; set; }
    }

And I have this function:

T Convert<T>(IDictionary<string, object> input, Type classType)
{
    // Do something.
    return T;
}

In javascript, it is very easy to do this task, but currently, I don't know how to achieve this task by using C#.

Can someone help me please?

Thank you,

Redplane
  • 2,971
  • 4
  • 30
  • 59
  • 2
    So your dictionary is what exactly? Is that just the primitive values displayed as json for some reason? Also `"age": "Nguyen"` ? It would be better if you created an MCVE, a method where you create the dictionary with values as you would receive it. Post that in the question. – Igor Mar 18 '17 at 17:37
  • Also why use generics here if you know what it is you want to convert to? Using generics serves no purpose. – Igor Mar 18 '17 at 17:38
  • I'm trying to build a media formatter for web api. – Redplane Mar 18 '17 at 17:46
  • That is not what I asked about... – Igor Mar 18 '17 at 17:48

1 Answers1

0

For those who wants to convert nested dictionary to a class.

Actually, my question is for making a new multipart/form-data formatter for Web API 2. I've tried some formatters made for Web API 2 but it failed to deal with nested class when a file is uploaded.

https://gist.github.com/Danielku15/bfc568a19b9e58fd9e80 How create a MultipartFormFormatter for ASP.NET 4.5 Web API

Here is my alternative multipart/form-data formatter.

My implementation may not be the best, but at least we can improve it later. Thanks to the miracle comes from Reflection.

Community
  • 1
  • 1
Redplane
  • 2,971
  • 4
  • 30
  • 59