1
    [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).

1
  • You should also consider initializing the Age property in the definition of the Person class. Commented Feb 13, 2018 at 16:26

1 Answer 1

2

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"
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

ohhh, I already tried that, but i didn't use the correct date format then. Thank you! Unfortunately there is a timer on accepting your answer, but this is it.

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.