Controller接受类为JSON参数

时间:2018-02-13 16:16:14

标签: c# asp.net json class

    [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?
    }
}

这是当前代码的简化版本。 我发帖的json:

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

如何通过自己接受自定义课程。 JSON?如果我取代公共年龄;公共DateTime年龄;然后这段代码工作,并正确解析日期。如果我没有发生运行时异常,因为“Object”为null(可能是由于内部反序列化错误)。

1 个答案:

答案 0 :(得分:2)

你发布的json需要匹配你想要绑定的模型结构(如果你只是想要内置的模型绑定就可以了)。

即。 尝试发帖:

-1 17 14 19 14 19 14 -1 
11 1 11 18 18 14 1 14 
11 14 1 14 12 1 17 13 
16 10 12 1 1 12 10 11 
11 11 14 -1 1 19 14 19 
15 12 -1 19 14 1 13 15 
13 -1 17 10 12 12 1 10 
1 19 15 18 12 11 13 1 
At [0, 0] number -1 is lower than [i * j]: 0
At [0, 7] number -1 is lower than [i * j]: 0
At [1, 6] number 1 is lower than [i * j]: 6
At [2, 2] number 1 is lower than [i * j]: 4
At [2, 5] number 1 is lower than [i * j]: 10
At [2, 7] number 13 is lower than [i * j]: 14
At [3, 3] number 1 is lower than [i * j]: 9
At [3, 4] number 1 is lower than [i * j]: 12
At [3, 5] number 12 is lower than [i * j]: 15
At [3, 6] number 10 is lower than [i * j]: 18
At [3, 7] number 11 is lower than [i * j]: 21
At [4, 3] number -1 is lower than [i * j]: 12
At [4, 4] number 1 is lower than [i * j]: 16
At [4, 5] number 19 is lower than [i * j]: 20
At [4, 6] number 14 is lower than [i * j]: 24
At [4, 7] number 19 is lower than [i * j]: 28
At [5, 2] number -1 is lower than [i * j]: 10
At [5, 4] number 14 is lower than [i * j]: 20
At [5, 5] number 1 is lower than [i * j]: 25
At [5, 6] number 13 is lower than [i * j]: 30
At [5, 7] number 15 is lower than [i * j]: 35
At [6, 1] number -1 is lower than [i * j]: 6
At [6, 3] number 10 is lower than [i * j]: 18
At [6, 4] number 12 is lower than [i * j]: 24
At [6, 5] number 12 is lower than [i * j]: 30
At [6, 6] number 1 is lower than [i * j]: 36
At [6, 7] number 10 is lower than [i * j]: 42
At [7, 3] number 18 is lower than [i * j]: 21
At [7, 4] number 12 is lower than [i * j]: 28
At [7, 5] number 11 is lower than [i * j]: 35
At [7, 6] number 13 is lower than [i * j]: 42
At [7, 7] number 1 is lower than [i * j]: 49
Total of numbers lower than the product of their row and column: 32