如何申请缩进序列化只是在一定的属性?在一、属性、序列化

2023-09-03 06:50:29 作者:君子动手不动口

我想在人类可读的方式序列化.NET对象到JSON,但我想有是否一个对象的属性或数组的元素最后一行自己的更多的控制。

I want to serialize .NET objects to JSON in a human-readable way, but I would like to have more control about whether an object's properties or array's elements end up on a line of their own.

目前我使用JSON.NET的 JsonConvert.SerializeObject(对象,格式化,JsonSerializerSettings)方法序列化,但似乎我只能适用 Formatting.Indented (个别行的所有元素)或者 Formatting.None (一切都在一行中没有任何空格)在全球范围格式规则整个对象。有没有在全球范围内使用的默认缩进,但将其关闭某些类或属性,例如一种方式使用属性或其他参数?

Currently I'm using JSON.NET's JsonConvert.SerializeObject(object, Formatting, JsonSerializerSettings) method for serialization, but it seems I can only apply the Formatting.Indented (all elements on individual lines) or Formatting.None (everything on a single line without any whitespace) formatting rules globally for the entire object. Is there a way to globally use indenting by default, but turn it off for certain classes or properties, e.g. using attributes or other parameters?

要帮助你理解这个问题,这里有一些例子输出。使用 Formatting.None

To help you understand the problem, here are some output examples. Using Formatting.None:

{"array":["element 1","element 2","element 3"],"object":{"property1":"value1","property2":"value2"}}

使用 Formatting.Indented

{
  "array": [
    "element 1",
    "element 2",
    "element 3"
  ],
  "object": {
    "property1": "value1",
    "property2":"value2"
  }
}

我想看到:

{
  "array": ["element 1","element 2","element 3"],
  "object": {"property1":"value1","property2":"value2"}
}

(我知道我的问题可能会略有与this 之一,但那里的说明完全错过了这一点,并没有真正提供一个有效的答案。)

(I realize my question may be slightly related to this one, but the comments there totally miss the point and don't actually provide a valid answer.)

推荐答案

一种可能性是写一个自定义的JSON的转换器,你需要特殊处理的具体类型和转换的格式为他们:

One possibility would be to write a custom Json converter for the specific types you need special handling and switch the formatting for them:

class Program
{
    static void Main()
    {
        var root = new Root
        {
            Array = new[] { "element 1", "element 2", "element 3" },
            Object = new Obj
            {
                Property1 = "value1",
                Property2 = "value2",
            },
        };
        var settings = new JsonSerializerSettings
        {
            Formatting = Formatting.Indented,
        };
        settings.Converters.Add(new MyConverter());

        string json = JsonConvert.SerializeObject(root, settings);
        Console.WriteLine(json);
    }
}

public class Root
{
    public string[] Array { get; set; }
    public Obj Object { get; set; }
}

public class Obj
{
    public string Property1 { get; set; }
    public string Property2 { get; set; }
}

class MyConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(string[]) || objectType == typeof(Obj);
    }

    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)
    {
        writer.WriteRawValue(JsonConvert.SerializeObject(value, Formatting.None));
    }
}

这将输出:

{
  "Array": ["element 1","element 2","element 3"],
  "Object": {"Property1":"value1","Property2":"value2"}
}