Reputation: 3363
I have an event that gives me a JSON string:
...
public delegate void DataReceivedHandler(string jsonString);
...
public event DataReceivedHandler OnDataReceived = null;
...
if(OnDataReceived != null)
{
OnDataReceived(jsonString);
}
...
That JSON string could be one of 3 different complex objects: LogOnMessage, LogOffMessage, or DataRequest. Each message has a unique set of fields and properties.
How can I determine which object type the JSON string resolves to?
I know I can write a method that iterates through the JProperty.Name of the JObject and find a match by iterating through my collection of objects and their meta-data, but my gut tells me this is a common challenge to be solved so it must be built in to Newtonsoft JSON .NET somewhere that I simply am overlooking or not understanding. It's probably better and faster than my solution would be too...
Upvotes: 2
Views: 3641
Reputation: 3363
I was finally able to detect object type by using JObjects and JsonSchemas.
Steps I Took:
Please note: the methods above have been moved to a separate Newtonsoft.Schema library. So my recommendation is to utilize the latest and greatest library.
private Newtonsoft.Json.Schema.JsonSchema _schema;
public static Newtonsoft.Json.Schema.JsonSchema Schema
{
get
{
if (_schema == null)
{
Newtonsoft.Json.Schema.JsonSchemaGenerator generator = new Newtonsoft.Json.Schema.JsonSchemaGenerator();
_schema = generator.Generate(typeof(DataResponse));
}
return _schema;
}
}
...
Newtonsoft.Json.Linq.JObject message = Newtonsoft.Json.Linq.JObject.Parse(json);
if(Newtonsoft.Json.Schema.Extensions.IsValid(message, DataResponse.Schema))
{...}
else if (Newtonsoft.Json.Schema.Extensions.IsValid(message, ServerStatus.Schema))
{...}
...
Upvotes: 3