inan
inan

Reputation: 188

Is there a setting on JSON Covert to throw any error if json is malformed

I have the following json which is malformed, which has missing property value, I want JSON.Convert to throw an error while deserializing, but instead phoneNumber is replaced with null when deserialize to strongly typed Object Person, and with dynamic type the value of phoneNumber is replaced with {}, I have tried various JsonSerializerSettings but doesn't seem to help throw an error, is there a way to do this

var json=    {
      "firstName": "joe",
      "lastName": "doe",
      "phoneNumber": ,
      "email": "[email protected]"
    }
JsonConvert.DeserializeObject<Person>(json);
JsonConvert.DeserializeObject<Dynamic>(json);

Upvotes: 0

Views: 55

Answers (1)

Gerrie Pretorius
Gerrie Pretorius

Reputation: 4131

This might be a bit of a work around, but you can mark it with an attribute that a value is required. Which migh or might not work for you depending on your exact case:

public class Videogame
{
    [JsonProperty(Required = Required.Always)]
    public string Name { get; set; }

    [JsonProperty(Required = Required.AllowNull)]
    public DateTime? ReleaseDate { get; set; }
}

Upvotes: 0

Related Questions