C# 从JSON确定对象类型
我有一个事件给了我一个JSON字符串:C# 从JSON确定对象类型,c#,json.net,deserialization,C#,Json.net,Deserialization,我有一个事件给了我一个JSON字符串: ... public delegate void DataReceivedHandler(string jsonString); ... public event DataReceivedHandler OnDataReceived = null; ... if(OnDataReceived != null) { OnDataReceived(jsonString); } ... 该JSON字符串可以是三个不同的复杂对象之一:LogOnMessa
...
public delegate void DataReceivedHandler(string jsonString);
...
public event DataReceivedHandler OnDataReceived = null;
...
if(OnDataReceived != null)
{
OnDataReceived(jsonString);
}
...
该JSON字符串可以是三个不同的复杂对象之一:LogOnMessage、LogOffMessage或DataRequest。每条消息都有一组唯一的字段和属性
如何确定JSON字符串解析为哪种对象类型?
我知道我可以编写一个方法,通过JObject的JProperty.Name进行迭代,并通过迭代我的对象集合及其元数据来找到匹配项,但我的直觉告诉我,这是一个需要解决的常见挑战,因此必须将其内置到Newtonsoft JSON.NET中,而我只是忽略或不理解它。它可能比我的解决方案更好更快…我终于能够使用JObjects和JsonSchemas检测对象类型 我采取的步骤:
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))
{...}
...
JSON中没有“对象类型”或任何其他类型的元数据。考虑将消息封装在某种信封或其他包装对象中。或者,将数据类型/元数据作为单独的参数/结构发送。当通过我们的内部应用程序执行此操作时,我们传递了类型为反序列化的请求标头(如果这是您的选项)。