且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Json.NET可以使用点表示法反序列化扁平化的JSON字符串吗?

更新时间:2021-10-14 23:47:01

是的,可以.您可以从 JsonConverter 派生一个类,并覆盖 CanConvert 方法转换为标记,您可以将Client类型.

Yes, you can. You would derive a class from JsonConverter and override the CanConvert method to indicae that you can convert the Client type.

然后,您将覆盖 ReadJson WriteJson 方法来读写以下字段JSON文字.

Then, you would override the ReadJson and WriteJson methods to read and write the fields of the JSON literal.

对于这样的JSON文字,您很有可能需要为Case类型创建一个JsonConverter,因为您将需要在序列化期间缓存Client对象的所有属性,直到您拥有足够的信息来实际创建Client实例.

For a JSON literal like this, it's more than likely you will need to create a JsonConverter for the Case type, as you will need to cache all the properties of the Client object during serialization until you have enough information to actually create the Client instance.

然后,您将在 Converters属性公开的实例 JsonSerializer 实例上的a>执行序列化/反序列化.

Then, you would call the Add method on the JsonConverterCollection instance exposed by the Converters property on the JsonSerializer instance you are using to perform your serialization/deserialization.

请注意,如果您需要对可能以这种方式表示的许多不同类执行此操作,则可以编写一个 JsonConverter实现,并让其扫描以下属性:财产.如果该属性具有属性并公开具有该属性的另一个对象,则它将期望读取/写入点符号.

Note that if you need to do this for a number of different classes that might be represented in this manner, then you can write one JsonConverter implementation, and have it scan for an attribute on the property. If the property has the attribute and exposes another object with properties, it would expect to read/write the dot-notation.

应该注意的是,当您使用点符号作为标识符时,这是非常不常见的.如果可能的话,在构造JSON文字的一侧,应该以这种方式进行操作:

It should be noted that while you are using the dot-notation for the identifier, it's very uncommon to do so. If possible, on the side that is constructing the JSON literal, it should be doing it in this manner:

{ 
    CaseName: "John Doe v. State", 
    CaseDate: "<some date>", 
    Client: 
    {
        FirstName: "John", 
        LastName: "Doe", 
        Email: "johndoe@gmail.com"
    }
} 

但这是假设您可以控制该目标.如果您不这样做,那么您将无能为力.

But that's assuming that you have control over that end. If you don't, then there's not much you can do.

如果您有控制权,那么以这种方式构造JSON文字将不需要自定义JsonConverter实现.

If you do have control, then constructing your JSON literals in that manner would negate the need for a custom JsonConverter implementation.