我希望以人类可读的方式将.NET对象序列化为
JSON,但我希望能够更好地控制对象的属性或数组的元素是否最终在自己的行上.
目前我正在使用JSON.NET的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 3" ],"object": { "property1": "value1","property2":"value2" } }
我想看到的:
{ "array": ["element 1","object": {"property1":"value1","property2":"value2"} }
解决方法
一种可能性是为您需要特殊处理的特定类型编写自定义Json转换器并切换它们的格式:
class Program { static void Main() { var root = new Root { Array = new[] { "element 1","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","Object": {"Property1":"value1","Property2":"value2"} }