如何使用JSON.NET在C#中序列化PSObject?

问题描述 投票:5回答:1

我正在编写一个Cmdlet,需要将对象结构传递给可能包含PSObjects的API客户端。目前,这些序列化作为包含CLIXML的JSON字符串。相反,我需要将它视为一个对象(包括PSObject.Properties中的NoteProperties作为属性,并递归地序列化它们的值)。

我尝试编写自己的JsonConverter但由于某种原因它只被调用顶级对象,而不是嵌套的PSObjects:

public class PSObjectJsonConverter : JsonConverter {

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
        if (value is PSObject) {
            JObject obj = new JObject();
            foreach (var prop in ((PSObject)value).Properties) {
                obj.Add(new JProperty(prop.Name, value));
            }
            obj.WriteTo(writer);
        } else {
            JToken token = JToken.FromObject(value);
            token.WriteTo(writer);
        }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
        throw new NotImplementedException();
    }

    public override bool CanRead {
        get { return false; }
    }

    public override bool CanConvert(Type objectType) {
        return true;
    }
}

此外,我正在使用CamelCasePropertyNamesContractResolver序列化骆驼案例。有没有办法让转换器尊重?

c# powershell json.net
1个回答
4
投票

以下转换器应正确序列化PSObject类型的递归嵌套对象:

public class PSObjectJsonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(PSObject).IsAssignableFrom(objectType);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var psObj = (PSObject)value;
        writer.WriteStartObject();
        foreach (var prop in psObj.Properties)
        {
            //Probably we shouldn't try to serialize a property that can't be read.
            //https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.pspropertyinfo.isgettable?view=powershellsdk-1.1.0#System_Management_Automation_PSPropertyInfo_IsGettable
            if (!prop.IsGettable)
                continue;           
            writer.WritePropertyName(prop.Name);
            serializer.Serialize(writer, prop.Value);
        }
        writer.WriteEndObject();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanRead { get { return false; } }
}

笔记:

  • WriteJson中,您将传入对象value序列化为每个属性的值。当然你的意思是prop.Value
  • 当传入的对象类型是true类型时,只返回CanConvert()中的PSObject,就可以避免在PSObject中为非WriteJson()类型实现默认序列化。
  • 当你打电话给JToken.FromObject(value)时,你没有使用传入的JsonSerializer serializer。因此,任何JsonSerializerSettings(包括转换器)都将丢失。从理论上讲,你可以使用JToken.FromObject(Object, JsonSerializer)来保存设置,但如果你这样做,你会遇到JSON.Net throws StackOverflowException when using [JsonConvert()]中描述的错误。幸运的是,由于我们现在在需要默认序列化时从false返回CanConvert,因此不再需要这样做。
  • 没有必要构建中间JObject。您可以直接写入JsonWriter,这将更有效。

更新:此外,我正在使用CamelCasePropertyNamesContractResolver序列化骆驼案例。有没有办法让转换器尊重?

一旦为类型引入了custom JsonConverter,您需要手动完成所有操作,包括重新映射属性名称。这是使用WriteJson()处理此问题的DefaultContractResolver.NamingStrategy版本:

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var psObj = (PSObject)value;
        writer.WriteStartObject();
        var resolver = serializer.ContractResolver as DefaultContractResolver;
        var strategy = (resolver == null ? null : resolver.NamingStrategy) ?? new DefaultNamingStrategy();

        foreach (var prop in psObj.Properties)
        {
            //Probably we shouldn't try to serialize a property that can't be read.
            //https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.pspropertyinfo.isgettable?view=powershellsdk-1.1.0#System_Management_Automation_PSPropertyInfo_IsGettable
            if (!prop.IsGettable)
                continue;
            writer.WritePropertyName(strategy.GetPropertyName(prop.Name, false));
            serializer.Serialize(writer, prop.Value);
        }
        writer.WriteEndObject();
    }

请注意,命名策略是在Json.NET 9.0.1中引入的,因此如果您使用的是早期版本,则需要创建自己的驼峰案例名称映射器,例如this answer中显示的映射器。

© www.soinside.com 2019 - 2024. All rights reserved.