Home Controller accept class as JSON Parameter
Reply: 1

Controller accept class as JSON Parameter

Shuzuka
1#
Shuzuka Published in 2018-02-13 16:16:14Z
    [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).

AdaTheDev
2#
AdaTheDev Reply to 2018-02-13 16:21:53Z

The json you post needs to match the model structure you want it to bind to (if you just want built-in model binding to just do it's thing).

i.e. try posting:

{
    "Name" : "Humberg",
    "Age" : {
        "Creation" : "2016-01-01T00:00:00.0000000-00:00"
    }
}
You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO