我的代码中有一个很大的任意JSON结构作为JObject引用。

我要序列化此结构,除非遇到包含名为JObject且值为type的属性的"encrypted",然后要在写入对象之前删除相邻的data属性。

换句话说,如果我遇到此问题:

{
  type: "encrypted",
  name: "some-name",
  data: "<base64-string>"
}

它将被序列化为:
{
  type: "encrypted",
  name: "some-name"
}

我无法更改结构,因此在更改之前将其克隆效率太低,因此我尝试使用JsonConverter,如下所示:
public class RemoveEncryptedDataSerializer : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(JObject);
    }

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

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var o = (JObject)value;
        if (o.Value<string>("type") != "encrypted")
        {
            o.WriteTo(writer);
            return;
        }

        var copy = o.DeepClone();
        copy["data"]?.Parent.Remove();
        copy.WriteTo(writer);
    }
}

但是,CanConvert函数似乎仅使用不是从JToken派生的类型来调用,因此从未调用过我的WriteJson函数。

还有另一种方法可以做到这一点吗?

编辑:这是一些可用于测试的代码:
[TestMethod]
public void ItShouldExcludeEncryptedData()
{
    var input = JObject.Parse(@"
    {
        a: {
            type: 'encrypted',
            name: 'some-name',
            data: 'some-data'
        }
    }");

    var expected = JObject.Parse(@"
    {
        a: {
            type: 'encrypted',
            name: 'some-name',
        }
    }");

    var output = input.ToString(Formatting.Indented, new RemoveEncryptedDataSerializer());

    Assert.AreEqual(
        expected.ToString(Formatting.Indented),
        output);
}

最佳答案

需要构建转换器以处理JToken,并且必须递归工作以确保编辑所有加密数据。

我能够使以下转换器正常工作:

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

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

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        JToken token = (JToken)value;
        if (token.Type == JTokenType.Object)
        {
            bool omitDataProperty = token.Value<string>("type") == "encrypted";

            writer.WriteStartObject();
            foreach (var prop in token.Children<JProperty>())
            {
                if (omitDataProperty && prop.Name == "data")
                    continue;

                writer.WritePropertyName(prop.Name);
                serializer.Serialize(writer, prop.Value);  // recurse
            }
            writer.WriteEndObject();
        }
        else if (token.Type == JTokenType.Array)
        {
            writer.WriteStartArray();
            foreach (var item in token.Children())
            {
                serializer.Serialize(writer, item);  // recurse
            }
            writer.WriteEndArray();
        }
        else // JValue
        {
            token.WriteTo(writer);
        }
    }
}

工作演示:https://dotnetfiddle.net/0K61Bz

如果要直接通过流使用JsonWriter,则可以将转换器中的逻辑重构为递归扩展方法,然后使用它。如果不使用串行器,则不需要转换器。
public static class JsonExtensions
{
    public static void RedactedWriteTo(this JToken token, JsonWriter writer)
    {
        if (token.Type == JTokenType.Object)
        {
            bool omitDataProperty = token.Value<string>("type") == "encrypted";

            writer.WriteStartObject();
            foreach (var prop in token.Children<JProperty>())
            {
                if (omitDataProperty && prop.Name == "data")
                    continue;

                writer.WritePropertyName(prop.Name);
                prop.Value.RedactedWriteTo(writer);  // recurse
            }
            writer.WriteEndObject();
        }
        else if (token.Type == JTokenType.Array)
        {
            writer.WriteStartArray();
            foreach (var item in token.Children())
            {
                item.RedactedWriteTo(writer);  // recurse
            }
            writer.WriteEndArray();
        }
        else // JValue
        {
            token.WriteTo(writer);
        }
    }
}

然后,您可以像这样使用它,其中stream是您的输出流,input是您的JObject:
using (StreamWriter sw = new StreamWriter(stream))  // or StringWriter if you prefer
using (JsonWriter writer = new JsonTextWriter(sw))
{
    writer.Formatting = Formatting.Indented;
    input.RedactedWriteTo(writer);
}

fiddle :https://dotnetfiddle.net/l949HU

关于c# - 在过滤掉某些属性的同时序列化JSON.NET JObject,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53669939/

10-12 20:47