最近在做一個需求,是Model底下會再有一個Model,但它的型別不會是固定的,於是我就在ASP.NET上做了簡單測試,發現真的能做到,底下是簡單的程式碼:

首先定義資料:

[JsonConverter(typeof(JsonStringEnumConverter))]
public enum TypeEnum
{
    TestModel = 0,
    TestModel2 = 2,
}

public class TestModel
{
    public string Name { get; set; } = string.Empty;

    public int Age { get; set; } = 18;
}

public class TestModel2
{
    public string NickName { get; set; } = string.Empty;

    public DateTime BirthDay { get; set; }
}


public class ResponseData
{
    public TypeEnum ModelType { get; set; }
    public string Code { get; set; } = string.Empty;
    public string Message { get; set; } = string.Empty;
    public dynamic Data { get; set; }
}

然後是Controller的寫法:

[HttpPost]
public IActionResult TD([FromBody]ResponseData rep)
{
    string jsonStr = rep.Data.ToString();
    object? result = null;
    switch (rep.ModelType)
    {
        case TypeEnum.TestModel:
            result = System.Text.Json.JsonSerializer.Deserialize<TestModel>(jsonStr);
            break;
        case TypeEnum.TestModel2:
            result = System.Text.Json.JsonSerializer.Deserialize<TestModel2>(jsonStr);
            break;
        default:
            throw new TypeAccessException();
    }
    return new JsonResult(result);
}

需要注意的是Enum那邊要加[JsonConverter(typeof(JsonStringEnumConverter))],這樣POST過來的資料才不會變成Null。