Steve H.
Steve H.

Reputation: 3363

Determining Object Type from JSON

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

Answers (1)

Steve H.
Steve H.

Reputation: 3363

I was finally able to detect object type by using JObjects and JsonSchemas.

Steps I Took:

  1. Added a Schema property to my message objects that exposed a _schema field. The first time the property is called, it populates _schema with the return value of JsonSchemaGenerator.Generate(object o).
  2. Convert the JSON string into a JObject via the JObject.Parse() static method.
  3. There is an extension method in Newtonsoft.Json.Schema.Extensions that can compare a JObject to a JsonSchema and determine if they match.

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

Related Questions