我想以一种人类可读的方式将.NET对象序列化为JSON,但是我想对对象的属性还是数组的元素以自己的一行结束进行更多控制。
目前,我正在使用JSON.NET的JsonConvert.SerializeObject(object, Formatting, JsonSerializerSettings)方法进行序列化,但似乎只能为整个对象全局应用Formatting.Indented(单个行中的所有元素)或Formatting.None(单个行中的所有元素,没有任何空格)格式化规则。有没有一种方法可以默认使用全局缩进,但是对于某些类或属性(例如,使用属性或其他参数)将其关闭?
JsonConvert.SerializeObject(object, Formatting, JsonSerializerSettings)
Formatting.Indented
Formatting.None
为了帮助您理解问题,以下是一些输出示例。使用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"} }
(我意识到我的问题可能与此问题稍有关系,但是那里的评论完全没有指出重点,实际上并没有提供有效的答案。)
一种可能是为需要特殊处理的特定类型编写定制的Json转换器,并切换其格式:
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"} }