简体   繁体   English

从JSON.NET检索动态类名?

[英]Retrieve Dynamic class name from JSON.NET?

I'm receiving messages over a network using JSON.NET. 我正在使用JSON.NET通过网络接收消息。 The message format is somewhat dynamic, in that the messages will be represented by many different classes, each inheriting from a parent message. 消息格式有些动态,因为消息将由许多不同的类表示,每个类都继承自父消息。 For example: 例如:

{
    MessageName: "MessageType1",
    Data1: 124,
    Data2: "Something"
}


{
    MessageName: "MessageType2",
    OtherData: "Some data",
    MoreData: "Even more",
    ANumber: 25
}

The problem I'm having is that in JSON.NET, I have no idea how to figure out the name of the class (MessageType1/MessageType2/etc) in order to deserialize it into an instance of the class without deserializing it twice. 我遇到的问题是,在JSON.NET中,我不知道如何找出类的名称(MessageType1 / MessageType2 / etc),以便将其反序列化为该类的实例而无需反序列化两次。 There's a few options I've considered; 我考虑了几种选择; the one I'm currently using is to use a container class containing the message name and the actual json message serialized to string, but this seems wasteful. 我当前正在使用的是使用一个包含消息名称和序列化为字符串的实际json消息的容器类,但这似乎很浪费。

Another method I've considered is deserializing into a string/string dictionary and then performing the population of the class on my own, which seems messy and unnecessary considering JSON.NET can do that for me... as long as I know the class first. 我考虑过的另一种方法是将其反序列化为字符串/字符串字典,然后自行执行该类的填充,考虑到JSON.NET可以为我做到这一点,这似乎很麻烦且不必要...只要我知道该类第一。

I'm really hoping there's an easy way to have JSON.NET figure out a class name by examining the MessageName property and then continue to populate a class after examining that one property. 我真的希望有一种简单的方法可以让JSON.NET通过检查MessageName属性来找出类名称,然后在检查该属性后继续填充类。

Thanks for the help! 谢谢您的帮助!

JSON can deserialize into a well known class only. JSON只能反序列化为知名类。 You need to specify the data layout (ie the class/type) 您需要指定数据布局(即类/类型)

There are two alternatives: 有两种选择:

1.) go one level deeper. 1.)更深一层。 Use the JSON Token parser to read the tokens from your JSON stream and act based on the tokens you find. 使用JSON令牌解析器从JSON流中读取令牌,并根据找到的令牌进行操作。

2.) as you suggested: Use a class layout flexible enough to hold all your possible variations like a key/value dictionary. 2)如您所建议:使用足够灵活的类布局来容纳所有可能的变体,例如键/值字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM