Home Controller accept class as JSON Parameter
Reply: 0

Controller accept class as JSON Parameter

user1136
1#
user1136 Published in June 20, 2018, 12:04 am
    [HttpPost]
    public bool Add([FromBody]Person Object)
    {
        if (!Object.IsValid()) return false;
        Repository.Add(Object);
        return true;
    }

public class Person : Model
{
    public Age Age;
    public string Name;

    public override bool IsValid()
    {
        if (Age == null) return false;

        return true;
    }
}

public class Age
{
    public DateTime Creation { get; set; }

    public Age() {}
    public Age(DateTime Creation)
    {
        this.Creation = Creation;
    }

    public int Compute()
    {
        return DateTime.Now.Year - Creation.Year; // Leap Year?
    }
}

This is a simplified version of the current code. The json i'm posting:

{
    "Age": "2016-01-01T00:00:00.0000000-00:00",
    "Name": "Humberg"
}

How is it possible to accept a custom class via. json? If i replace public Age Age; with public DateTime Age; then this code works, and the date get's parsed correctly. If i don't a runtime exception occurs because "Object" was null (probably due to an internal deserialization error).

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.310405 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO