0

In the Json deserialization model, I have a class member that can be a single item or an array, thus I use a JsonConverter to deal with it. However, sometimes the entire property is missing in the response as well. The model has a property that the Json response sometimes does not, so I am using [JsonProperty(Required = Required.Always)].

public class Reservation
{

    [JsonConverter(typeof(SingleOrArrayConverter<Resource_Reservation>))]
    [JsonProperty(Required = Required.Always)]
    public List<Resource_Reservation> resource_reservation { get; set; }

The problem is when missing class property passes through the ReadJson method in the JsonConverter, it raises exception.

Exception in JsonConverter

My question is whether I can add missing property logic check in the JsonConverter, or do I need to deal with the exception as is.

ProgrammerBret
  • 137
  • 2
  • 12
  • 1
    Please add a [mcve] showing your JSON and code (as **text** rather than a screen shot). (See [ask].) If the property is entirely missing from the JSON then `SingleOrArrayConverter.ReadJson()` will never get called. Incidentally, `[JsonProperty(Required = Required.Always)]` explicitly tells Json.NET to throw an exception if the `"resource_reservation"` property is missing. If you don't want that you should remove [`Required = Required.Always`](https://www.newtonsoft.com/json/help/html/JsonPropertyRequired.htm). – dbc Feb 03 '21 at 20:19
  • I will include the raw code next time. I can assure that the property is missing from the Json return,as I see the return in postman for the query. I do need a way to determine if the "resource_reservation" is missing, so that is why I set the property to required. – ProgrammerBret Feb 04 '21 at 17:35
  • @ProgrammerBret - well if you set the property as `Required` then Json.NET will throw an exception, that's the functionality of `Required`. Is your question, *How can I track missing members while deserializing an object, rather than aborting deserialization via an exception as is done by the `Required = Required.Always` functionality?* If so then that has nothing to do with `SingleOrArrayConverter<>`. A [mcve] would help clarify the situation. – dbc Feb 04 '21 at 18:28
  • This could be a more focused question. From previous research it was my understanding that if the Json was missing properties that the model has, we are to set to `Required.Always`. However I can bypass this error if I set to `Required.Default`, but from there I need to do a null check on that property. – ProgrammerBret Feb 04 '21 at 19:44
  • Then maybe you want [How to configure JSON.net deserializer to track missing properties?](https://stackoverflow.com/q/30300740/3744182). – dbc Feb 04 '21 at 23:14
  • *"I will include the raw code next time"* . *"This could be a more focused question"* You know you can edit your question, right? If important details are missing, by all means add them! – Brian Rogers Feb 05 '21 at 16:23

0 Answers0