0

注意:我使用的System.Text.Json不是JSON.NET已经回答了类似的问题。我需要相同的答案,但对于System.Text.Json. 我想将我的课程写成 Json 并确保它是人类可读的。为此,我在选项中将缩进设置为 true。但是,该类包含一个List<double>我不想缩进的属性,因为它使文件很长。

所以我有这个:

public class ThingToSerialize
{
    public string Name {get;set;}
    //other properties here
    public List<double> LargeList {get;set;}
};

var thing = new ThingToSerialize {Name = "Example", LargeList = new List<double>{0,0,0}};
var options = new JsonSerializerOptions
{
    WriteIndented = true
};

options.Converters.Add(new DontIndentArraysConverter());

var s = JsonSerializer.Serialize(thing, options);

我希望它像这样序列化:

{
    "Name": "Example",
    "LargeList ": [0,0,0]
}

不是这个(或类似的东西):

{
    "Name": "Example",
    "LargeList ": [
        0,
        0,
        0
    ]
}

我写了一个JsonConverter来实现这一点:

public class DontIndentArraysConverter  : JsonConverter<List<double>>
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(List<double>);
    }

    public override List<double> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return JsonSerializer.Deserialize<List<double>>(reader.GetString());
    }

    public override void Write(Utf8JsonWriter writer, List<double> value, JsonSerializerOptions options)
    {
        var s = JsonSerializer.Serialize(value);
        writer.WriteStringValue(s);
    }

}

但是,这会将数组写入我并不真正想要的字符串。最好的方法是什么?

即你得到“[1,2,3]”而不是[1,2,3]

其次,writer传递给Write函数的对象具有Options属性,但不能更改。因此,如果我使用 writer 对象手动写出数组,它会缩进。

4

1 回答 1

1

感谢您的想法,我根据转换器提示编写了自己的序列化程序

这个想法是在转换期间写入一个临时值,将正确的数组放入临时字典并稍后替换它们

对你来说有点晚了,但也许它可以帮助其他人

public class CustomSerializer : IDisposable
{
    private readonly Dictionary<string, string> _replacement = new Dictionary<string, string>();

    public string Serialize<T>(T obj)
    {
        var converterForListInt = new DontIndentArraysConverterForListInt(_replacement);

        var options = new JsonSerializerOptions
        {
            IgnoreNullValues = true,
            WriteIndented = true
        };
        
        options.Converters.Add(converterForListInt);

        var json = JsonSerializer.Serialize(obj, options);
        foreach (var (k, v) in _replacement)
            json = json.Replace(k, v);
        return json;
    }

    public void Dispose()
    {
        _replacement.Clear();
    }
    
    public class DontIndentArraysConverterForListInt  : JsonConverter<List<int>>
    {
        private readonly Dictionary<string, string> _replacement;

        public DontIndentArraysConverterForListInt(Dictionary<string, string> replacement)
        {
            _replacement = replacement;
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(List<int>);
        }

        public override List<int> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            return JsonSerializer.Deserialize<List<int>>(reader.GetString());
        }

        public override void Write(Utf8JsonWriter writer, List<int> value, JsonSerializerOptions options)
        {
            if (value.Count > 0)
            {
                var key = $"TEMPLATE_{Guid.NewGuid().ToString()}";
                var sb = new StringBuilder();
                sb.Append('[');
                foreach (var i in value)
                {
                    sb.Append(i);
                    sb.Append(',');
                }
                sb.Remove(sb.Length - 1, 1); // trim last ,
                sb.Append(']');
                _replacement.Add($"\"{key}\"", sb.ToString());
                
                //
                writer.WriteStringValue(key);
            }
            else
            {
                // normal
                writer.WriteStartArray();
                writer.WriteEndArray();
            }
        }
    }
}
于 2021-11-02T19:36:59.810 回答