0

I'm using .Net 5 and I have a data model with a string type property. When I use it in controller and user send a number or other type of value, I hope it can be automatically convert to string type instead of throw an error, how should I do that?

Thank you.

The model is like this:

public class Product
{
    public string ProductNo { get; set; }
    public string ProductName { get; set; }
}

and the input could be

[
    {
        "productNo": 123456,
        "productName": "abc"
    },
    {
        "productNo": "S123",
        "productName": "def"
    }
]
qwer11121
  • 138
  • 2
  • 15
  • `public object ProductNo { get; set; }` and then call Product.ProductNo.ToString()? – Leisen Chang Oct 18 '21 at 03:56
  • @LeisenChang this model is mapped to SQL database table NVARCHAR type column in EF core, does "object" working in this situation? – qwer11121 Oct 18 '21 at 05:13
  • https://stackoverflow.com/questions/59097784/system-text-json-deserialize-json-with-automatic-casting – Artur Oct 18 '21 at 05:57

1 Answers1

0

I found a workaround by using NewtonsoftJson instead of Text.Json

https://stackoverflow.com/a/58155409/5886375

qwer11121
  • 138
  • 2
  • 15