简体   繁体   中英

Newtonsoft.JSON serialization results in a sole string with the object's type

I have an object of class ProcessStartInfo

ProcessStartInfo psi = new ProcessStartInfo()
{
    FileName = "path",
    Arguments = "args",
    UseShellExecute = false,
    RedirectStandardError = true,
    CreateNoWindow = true,
    Verb = "runas"
};

And for logging purpose I want serialize it to JSON. My code:

string json = JsonConvert.SerializeObject(psi);

json contains:

"System.Diagnostics.ProcessStartInfo"

How to serialize properties intead type name?

As @CodeCaster specified in the comment, the issue is with [TypeConverter(typeof(ExpandableObjectConverter))] , you need to create new JsonObjectContract for that ' ExpandableObjectConverter ' attribute assigned to type.

New contract resolver can be created for the type having 'ExpandableObjectConverter' attibute :

public class SerializableExpandableContractResolver : DefaultContractResolver
{
    protected override JsonContract CreateContract(Type objectType)
    {
        if (TypeDescriptor.GetAttributes(objectType).Contains(new TypeConverterAttribute(typeof(ExpandableObjectConverter))))
        {
            return CreateObjectContract(objectType);
        }
        return base.CreateContract(objectType);
    }
}

Now, you can use above contract resolver while serializing in following way:

string json = JsonConvert.SerializeObject(psi,
                new JsonSerializerSettings() {ContractResolver = new SerializableExpandableContractResolver()});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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