Home > OS >  Newtonsoft JsonSerializer: How to make it fail if non-nullable string is null?
Newtonsoft JsonSerializer: How to make it fail if non-nullable string is null?

Time:11-15

I find it difficult to force the deserialize operation to actually fail if the data doesn't match exactly what's expected for the output class.

class ContainerClass {
   string SomeString { get; set; } // <-- not nullable
}

Json file :

[
  {
    "SomeString": null, // <-- null
  }
]

Deserialize function :

using JsonTextReader reader = new JsonTextReader(file); // <-- the file I got from my controller.

var serializer = Newtonsoft.Json.JsonSerializer.Create(); // or new Serializer, whatever
serializer.MissingMemberHandling = MissingMemberHandling.Error;

return serializer.Deserialize<Collection<RegisterImportItem>>(reader);

I want the deserialize to fail if the string has a null value. The code above succeeds silently and places a null value in the non-nullable field. The horror!

I'd like to achive that by configuring the serializer (as in : I don't want to add a decorator above the field itself ).

Long things short: I want all non-nullable fields to fail if the value is null, no matter what.

CodePudding user response:

JSON.NET was written well before nullable reference types were a thing. The best way to do this is to use the JsonProperty attribute.

Annotate the property with JsonProperty

[JsonProperty(Required = Required.DisallowNull)]

CodePudding user response:

your json is array but you are trying to deserialize object, try this code

    var json=@"[
  {
    ""SomeString"": null, // <-- null
    ""JustString"": ""test"" 
  }
]";
    var test = JsonConvert.DeserializeObject<ContainerClass[]>(json);

and fix the class by adding an accessor

public class ContainerClass {
  public  string SomeString { get; set; } 
 public string JustString { get; set; }
}
  • Related