使用Json.NET序列化为json字符串时,为什么缺少DriveInfo的属性? [英] Why are DriveInfo's properties missing when serializing to json string using Json.NET?

查看:86
本文介绍了使用Json.NET序列化为json字符串时,为什么缺少DriveInfo的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用此代码将DrivInfo序列化为Json字符串,只会返回"name"属性:

Attempting to serialize DrivInfo to a Json string with this code only return the "name" property:

DriveInfo dr = new DriveInfo("C");    
string json = Newtonsoft.Json.JsonConvert.SerializeObject(dr);

字符串结果仅是: {"_name":"C:\"}

DrivInfo已密封,因此我无法更改任何内容.有没有一种方法可以排除包装?

DrivInfo is sealed so I cannot change anything. Is there a way to do it excluding wrapping?

推荐答案

该类包含其自己的自定义序列化,该序列化指定仅应包含_name字段.其他属性未存储在类中.它们是由环境决定的,因此不能用反序列化的值替换.

The class contains its own custom serialization which specifies that only the _name field should be included. The other properties aren't stored in the class. They're determined by the environment, so they can't be replaced with deserialized values.

源代码:

private const String NameField = "_name";  // For serialization

    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
    {
        // No need for an additional security check - everything is public.
        info.AddValue(NameField, _name, typeof(String));
    }

其他属性是通过实际检查DriveInfo引用的驱动器确定的.诸如TotalFreeSpaceTotalFreeSize之类的属性可能会随时更改,并且可能不会(可能不会)应用在可以反序列化该类的另一台计算机上.

Other properties are determined by actually inspecting the drive referenced by the DriveInfo. Properties like TotalFreeSpace and TotalFreeSize can change from moment to moment and may not (probably don't) apply on another computer where the class could be deserialized.

如果您可以将整个序列序列化并在其他位置反序列化,则可以创建该类的反序列化实例,在该实例中所有属性值都是错误的,例如,他们实际上在另一台计算机上描述了c:驱动器.但是,该类的目的是在执行代码的计算机上返回有关驱动器的信息.

If you could serialize the whole thing and deserialize it someplace else, then it would be possible to create a deserialized instance of the class where all of the property values are wrong, because, for example, they actually describe the c: drive on another computer. But the purpose of the class is to return information about a drive on the computer where the code is executing.

如果您想传递这些数据,则始终可以创建自己的类并对其进行序列化.

If you want to pass that data around then you can always create your own class and serialize that.

这篇关于使用Json.NET序列化为json字符串时,为什么缺少DriveInfo的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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