Your difficulty is that DriveInfo
implements the ISerializable
interface for custom serialization, and Json.NET respects this interface by default, using it to serialize and deserialize the type. And since DriveInfo
is defined entirely by the name of the drive, that's all that it's custom serialization code stores into the serialization stream.
Since you just want to dump the properties of DriveInfo
and do not care about deserialization, you can disable use of ISerializable
by setting DefaultContractResolver.IgnoreSerializableInterface = true
. However, if you do this, you'll get an infinite recursion serializing dr.RootDirectory.Root.Root...
. To work around this, you could create a JsonConverter
for DirectoryInfo
:
public class DirectoryInfoConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(DirectoryInfo);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var token = JToken.Load(reader);
return new DirectoryInfo((string)token);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}
}
Then you could do:
DriveInfo dr = new DriveInfo("C");
var settings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver { IgnoreSerializableInterface = true },
Converters = new [] { new DirectoryInfoConverter() },
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(dr, Formatting.Indented, settings);
But at this point, it's probably easier just to serialize an intermediate anonymous type:
var json = JsonConvert.SerializeObject(
new
{
Name = dr.Name,
DriveType = dr.DriveType,
DriveFormat = dr.DriveFormat,
IsReady = dr.IsReady,
AvailableFreeSpace = dr.AvailableFreeSpace,
TotalFreeSpace = dr.TotalFreeSpace,
TotalSize = dr.TotalSize,
RootDirectory = dr.RootDirectory.ToString(),
VolumeLabel = dr.VolumeLabel
},
Formatting.Indented);
(Of course, you won't be able to deserialize it in this format.)