How to check if Json matches a specific type of C #?

The action of my ASP.NET MVP application returns JSON by serializing one of several C # objects depending on the circumstances (if an error occurs, one data type, if one data type was received, etc.).

When I try to use JSON in a Windows C # service, I have problems trying to figure out what type of JSON is being returned. Unfortunately, because of what I saw, JSON serializers (JSON.Net and any other RestSharp applications) have no problem creating an empty object if none of the JSON matches.

I understand why this happens, but I'm confused about how to find out if the values ​​serialized from JSON are legitimate, or if none of the JSON properties match, and the serializer just created an empty object.

Does anyone know how I would determine if there is a match between JSON and the type I'm trying to deserialize?

+4
source share
2 answers

I would suggest using a catch try block if your deserialization will cause an invalid argument exception then the string was not in the correct format. If you are using System.Web.Script.Serialization

JavaScriptSerializer sel = new JavaScriptSerializer(); try { return sel.Deserialize<List<YourObjectType>>(jSONString); } catch(System.ArgumentException e) { return null; } 
0
source

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) { } 
0
source

All Articles