I don’t know exactly how to match between JSON and C # types. But if you want to check all properties from the corresponding values in JSON, you can do Json Serialization Sttributes :
Here I have a C # type:
[JsonObject(ItemRequired = Required.Always)] public class Event { public string DataSource { get; set; } public string LoadId { get; set; } public string LoadName { get; set; } public string MonitorId { get; set; } public string MonitorName { get; set; } public DateTimeOffset Time { get; set; } public decimal Value { get; set; } }
I decorated this type with the [JsonObject(ItemRequired = Required.Always)] attribute, which requires all properties to be populated with the corresponding properties from the JSON text.
There are three important points:
- If you try to deserialize JSON text that does not contain properties similar to the Event class, it will throw an exception.
- If JSON contains these properties but does not contain values, it will undergo deserialization.
- If the JSON text contains the same properties as the Event class but contains additional properties, it will still be deserialized.
Here is a sample code:
var message = @"{ 'DataSource':'SomeValue','LoadId':'100','LoadName':'TEST LOAD','MonitorId':'TEST MONITOR','MonitorName':'TEST MONITOR','Time':'2016-03-04T00:13:00','Value':0.0}"; try { var convertedObject = JsonConvert.DeserializeObject<Event>(message); } catch (Exception ex) { }
source share