在JSON反序列化期间确定类型 [英] Determine type during json deserialize

查看:436
本文介绍了在JSON反序列化期间确定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一种协议,其中接收方将接收某些指定的自定义类型(当前为5,但可能为10-20)的json消息.我正在努力想出一个最优/快速的解决方案,该解决方案将自动反序列化json并返回正确类型的对象.

I'm working on a protocol in which the receiver will receive json messages of certain specified custom types (currently 5, but could be 10-20). I'm struggling to come up with an optimal/fast solution which will automatically deserialize the json and return the correct type of object.

示例:

public class MessageA
{
    public string Message;
} 

public class MessageB
{
    public int value;
}

public class MessageC
{
    public string ValueA;
    public string ValueB;
}

理想情况下,方法应类似于

Ideally, the method should be like

 Object Deserialize(string json);

,它将返回三种消息类型之一,或者返回null-如果发生解析错误/json与任何预定义类型都不匹配.

and it will return one of the three message types OR null - in case there was a parsing error/the json didn't match any of the predefined type.

更新:我可以控制发送者/接收者以及协议设计.

UPDATE: I have control over sender/receiver as well as the protocol design.

推荐答案

如果消息可以指定其类型,将很有帮助.否则,您必须从某些属性或其他属性中推断出它.

It would be helpful if the message could specify its type. Otherwise you have to infer it from some property or another.

您可以在序列化时使用消息包装器类,如下所示:

You could use a message wrapper class when serializing, like this:

public class MessageWrapper<T>
{
    public string MessageType { get { return typeof(T).FullName; } }
    public T Message { get; set; }
}

因此,如果您的类Name具有FirstLast属性,则可以像这样序列化它:

So if you have a class Name with a First and Last property, you could serialize it like this:

var nameMessage = new MessageWrapper<Name>();
nameMessage.Message = new Name {First="Bob", Last = "Smith"};
var serialized = JsonConvert.SerializeObject(nameMessage);

序列化的JSON是

{"MessageType":"YourAssembly.Name","Message":{"First":"Bob","Last":"Smith"}}

反序列化时,首先将JSON反序列化为这种类型:

When deserializing, first deserialize the JSON as this type:

public class MessageWrapper
{
    public string MessageType { get; set; }
    public object Message { get; set; }
}

var deserialized = JsonConvert.DeserializeObject<MessageWrapper>(serialized);

MessageType属性中提取消息类型.

Extract the message type from the MessageType property.

var messageType = Type.GetType(deserialized.MessageType);

现在您知道类型了,您可以反序列化Message属性.

Now that you know the type, you can deserialize the Message property.

var message = JsonConvert.DeserializeObject(
    Convert.ToString(deserialized.Message), messageType);

messageobject,但是您可以将其强制转换为Name或它实际使用的任何类.

message is an object, but you can cast it as Name or whatever class it actually is.

这篇关于在JSON反序列化期间确定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆