Search code examples
c#jsonserializationjson.netjsonserializer

Why are DriveInfo's properties missing when serializing to json string using Json.NET?


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);

The string result is only: {"_name":"C:\"}

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


Solution

  • 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.

    From the source code:

    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));
        }
    

    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.

    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.