C# Json序列化的格式化问题
问题来源: 客户要求传送给他的JSON文件的float型格式化为2位小数,数值型有30-40个栏位,一个一个修改也不是很好.
bing和百度找到的方式都是自己定义一个JsonConverter,进行格式化.
找到的都是在字符串两边加++的例子,核心转化的代码如下:
class StringFormatConverter : JsonConverter { public string Format { get; set; } public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(string.Format(Format, value)); } public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotSupportedException(); } public override bool CanConvert (Type objectType) { return objectType == typeof(string); } }
Console.WriteLine(JsonConvert.SerializeObject(new List<Foo> { new Foo { FooId = 1, Name = "FooName", Description = "Bla bla bla" } }, new JsonSerializerSettings { Converters = { new StringFormatConverter { Format = "++{0}++" } } }));
按照它的思路进行修改一版(此时的格式化格式写死的,准备搞定之后再修改):
class FloatFormatConverter : JsonConverter { public string Format { get; set; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(string.Format("{0:f2}", value)); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotSupportedException(); } public override bool CanConvert(Type objectType) { return objectType == typeof(float) || objectType == typeof(double); } }
发现问题: 1)数字变成了字符 (比如: "Height": "28.2") 2)Json的整体的换行格式化(Formatting.Indented) 需要加进去
多次尝试之后的最终版本,达到了最后的要求
context.Response.Write(JsonConvert.SerializeObject(new { errcode = 1000, errmsg = edi }, Formatting.Indented, new FloatFormatConverter { Format = "0.##" })); class FloatFormatConverter : JsonConverter { public string Format { get; set; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(Convert.ToDouble(((float)value).ToString(Format))); }
终于搞定了.
参考网站
https://stackoverflow.com/questions/15810087/how-to-format-properties-that-are-only-string-in-an-object-while-converting-to-j