-1

I have the class

class Temp {
    public string Field1 { get; set; }
    public int Field2 { get; set; }
    public bool Field3 { get; set; }
    ...
}

In some cases in my program "{}" string deserializing to Temp class with Newtonsoft.Json, i.e

var obj = JsonConvert.DeserializeObject("{}", typeof(Temp));

I expect to get null or exception, but I got an instance of Temp class with default values, i.e

{
    Field1: "",
    Field2: 0,
    Field3: false,
}

Can I change this behavior?

  • "I expect to get null or exception" - why do you expect that? Why would you expect to get a null reference when the JSON value represents an object, and why would you expect to get an exception just because the properties aren't present? (Would you also expect to get an exception if Field1 and Field2 were specified, but not Field3?) I suspect it's possible to configure Json.NET to require some (or all) properties to be in the JSON, but that's not the default. – Jon Skeet Jun 14 '23 at 10:31
  • 3
    You can use `JsonProperty` with the `Required` attribute to specify mandatory fields if you want an exception. If *no* fields are mandatory, though (as they aren't here), then an empty, default object is clearly distinct from a literal `null` (which would indeed be deserialized as a .NET `null`), and it's just as legal as writing `new Temp()` is. – Jeroen Mostert Jun 14 '23 at 10:42
  • 1
    deserialise creates a new object from class and populate values. since you have nothing in json - there would be object to match a new Temp() but, if you will pass empty string - you will get NULL value, if you will pass NULL - you will get exception – Power Mouse Jun 14 '23 at 15:16
  • If you want to force Json.NET to throw an error when the JSON is missing some properties, you may mark each properties with `[Required]` or `[JsonProperty(Required = Required.Always)]` as mentioned by @JeroenMostert, or you could use a custom contract resolver to do this automatically as described in [this answer](https://stackoverflow.com/a/29660550/3744182) to [Json.NET require all properties on deserialization](https://stackoverflow.com/q/29655502/3744182). – dbc Jun 14 '23 at 15:54

1 Answers1

0

You could use Json.Net Schema to make sure that received json contains everything you need.

Here is a simple application how to use it

static JSchemaGenerator generator = new();
static JSchema schema = generator.Generate(typeof(Temp));
public static void Main()
{
    var jsons = new[] {
        "{}",
        "{'Field1': \"1\"}",
        "{'Field1': \"1\", 'Field2': 2}",
        "{'Field1': \"1\", 'Field2': 2, 'Field3': 'false'}",
        "{'Field1': \"1\", 'Field2': 2, 'Field3': false}",
        "{'Field1': \"1\", 'Field2': 2, 'Field3': false, 'Field4': 4.0}",
    };
    
    foreach(var json in jsons)
    {
        var semiParsedJson = JObject.Parse(json);
        Console.WriteLine($"{json} is valid: {semiParsedJson.IsValid(schema)}");
    }
}

and here is the output

{} is valid: False
{'Field1': "1"} is valid: False
{'Field1': "1", 'Field2': 2} is valid: False
{'Field1': "1", 'Field2': 2, 'Field3': 'false'} is valid: False
{'Field1': "1", 'Field2': 2, 'Field3': false} is valid: True
{'Field1': "1", 'Field2': 2, 'Field3': false, 'Field4': 4.0} is valid: True

Dotnet Fiddle link

Peter Csala
  • 17,736
  • 16
  • 35
  • 75