Home > Back-end >  Can I make deserialization fail for mapping a quoted number to a int?
Can I make deserialization fail for mapping a quoted number to a int?

Time:01-25

I have the following json payload:

{
  "s": "hfhryru567riuey4",
  "t": 1643184327,
  "b": "1c4736b4-db30-43a5-ba49-d9e5c1904c05",
  "p": "1-1",
  "a": "V"
}

Which I deserialize to the following class, using newtonsoft:

public class ValidationModel
{
    [JsonRequired]
    [Required(AllowEmptyStrings = false)]
    public string s { get; set; }

    [JsonRequired]
    public int t { get; set; }

    [JsonRequired]
    public System.Guid b { get; set; }

    [JsonRequired]
    [Required(AllowEmptyStrings = false)]
    public string p { get; set;}

    [JsonRequired]
    [Required(AllowEmptyStrings = false)]
    public string a { get; set; }
}

The problem is, that when I try to give the following json, where t is in a string, I want it to fail:

{
  "s": "hfhryru567riuey4",
  "t": "1643184327",
  "b": "1c4736b4-db30-43a5-ba49-d9e5c1904c05",
  "p": "1-1",
  "a": "V"
}

But right now, it just seems like it is casting t to from a string to a number. I need it to fail in this case, since I am using the deserialization to confirm that the payload is in the right form.

How can I do this?

CodePudding user response:

I would use a json constructor

public class ValidationModel
{
    public int t { get; set; }

    // all your another properties


    [JsonConstructor]
    public  ValidationModel (JToken t)
    {
        if (t.Type == JTokenType.Integer) this.t = (int)t;
           else  throw new JsonException("t property should be int type"); 
        
    }
}
  • Related