开发者

How can I check if Json matches a specific C# type?

My Asp.Net MVC application action is returning JSON by serializing one of several C# objects, depending on the circumstances (if an error occurred, one data type if one type of data was retrieved, etc...).

When I try to consume the JSON in a C# windows service, I am having trouble trying to figure out what type of JSON is being returned. Unfortunately from what I have seen, JSON serializers (JSON.Net and whatever RestSharp uses) all have no problem creating开发者_如何转开发 an empty object if none of the JSON matches.

I understand why this happens, but I am confused on how to figure out if the values serialized from JSON are legit, or if none of the JSON properties matched and the serializer just created an empty object.

Does anyone know how I would determine if a match exists between JSON and the type I am trying to deserialize to?


I don't know exactly how to match between JSON and C# type. But if you want to check is all properties from match appropriate values in JSON you can do Json Serialization Sttributes:

Here I have 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 that type with attribute [JsonObject(ItemRequired = Required.Always)] which requires from all properties to be populated with appropriate properties from JSON text.

There are three imporatnt things:

  • If you try to deserialize JSON text which doesn't contain properties like in Event class it will throw exception.
  • If JSON contains these properties, but doesn't contain values it will pass deserialization.
  • If JSON text contains same properties as Event class but contains additional properties too, it will still pass deserialization.

Here is example 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)
{

}


I would recommend using a try and catch block, if your deserialization will throw invalid argument exception then the string was not in proper 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜