2

I have a user class like

public class User
{
  public string UserName {get;set;}
  public string Application {get;set;}
}

Now, I am using it like

var jsonSerializer = new DataContractJsonSerializer(typeof(User));
var objApp = (User)jsonSerializer.ReadObject(new MemoryStream(Encoding.Unicode.GetBytes(JsonInput)));

But my JSON JsonInput doesn't contain both values for example Application is not available in the JSON. This still serializes with on only UserName. The JSON and class above is an example, there are quite a few members for me to check them individually ! I want to make sure, the JSON contains all the members of the class, if not , throw error.

But I can't seem to find way. What am I missing here?

dbc
  • 104,963
  • 20
  • 228
  • 340
Milind Thakkar
  • 980
  • 2
  • 13
  • 20

1 Answers1

2

If you use Newtonsoft (which you can install with Install-Package Newtonsoft.Json) - You can set the MissingMemberHandling property of the settings;

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

Then pass it;

    var userObj = JsonConvert.DeserializeObject<User>(jsonInput, settings);

If you must use Datacontract instead, you can decorate your User object with required attributes;

 [DataMember(IsRequired=true)]
 public string? RequiredProperty { get; set; }
Milney
  • 6,253
  • 2
  • 19
  • 33
  • Newtonsoft is pretty much the default json serialiser now. Even Microsoft use it internally. Your much better off switching to this and forgetting the DataContractJsonSerializer ever existed – Liam Aug 08 '17 at 08:05
  • ^ This. There is no reason to prefer the DataContract one, but I put it there just in case as I know some projects can have weird constraints @S – Milney Aug 08 '17 at 08:06
  • 1
    If you want to apply `[DataMember]` to members, it's also necessary to apply `[DataContract]` to the type itself, which makes serialization opt-in rather than opt-out. – dbc Aug 08 '17 at 08:10
  • ^ Indeed, sorry forgot about that as I do not use it much – Milney Aug 08 '17 at 08:11
  • @Milney Thanks for both points and detailed explanation. I am away from my work machine at the moment. Will check tomorrow and update you. – Milind Thakkar Aug 09 '17 at 18:06