2

I have a Json serialized configuration in which I need to deserialize the object using

JsonConvert.DeserializeObject<>(jsonConfig)

to Myclass list. In jsonConfig there may be some properties missing where I got an exception like below.

Required property 'xxx' not found in JSON. Path '[0].yyy',

So is there any way to handle the undefined values while deserializing an object in c#?

Rahul Nikate
  • 6,192
  • 5
  • 42
  • 54
Yuvaranjani
  • 300
  • 2
  • 12
  • Json.Net will only throw this exception if you have properties in your model which are marked as required, e.g. `[JsonProperty(Required = Required.Always)]`. So the obvious solution is to remove the requirement. – Brian Rogers Sep 20 '19 at 21:52

2 Answers2

1

You need to make those properties nullable in object model class like below.

 [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
 public int? someProperty { get; set; }

Also if property itself is missing from class while deserializing then you can do like below:

 JsonSerializerSettings settings = new JsonSerializerSettings();
 settings.MissingMemberHandling = MissingMemberHandling.Ignore;

 var deserializedObj = JsonConvert.DeserializeObject<MyModelClass>(jsonConfig, settings);
Rahul Nikate
  • 6,192
  • 5
  • 42
  • 54
  • Thanks Rahul. this NullValueHandling is only for the property which has null value right. if the property itself missing means is there any way to handle or do we need any Custom JsonConverter for handling the undefined values? – Yuvaranjani Sep 19 '19 at 08:40
  • 1
    it doesn't work for me still it's throwing the same exception – Yuvaranjani Sep 19 '19 at 10:19
  • Please update your question and add your model class. – Rahul Nikate Sep 19 '19 at 10:54
0

undefined is not a valid json value, even though it is valid in javascript. Please check https://api.jquery.com/jQuery.parseJSON/

  • For json, use null instead of undefined: { "something": null }
awais
  • 492
  • 4
  • 17