将对象的属性为数值型的转换为String
将对象的属性为数值型的转换为String
1、新建一个类
//注意:此处为待转换的类型,return true 不好用,必须将待转换的类型一一列出
using Newtonsoft.Json; namespace WinFormsApp1.Common { public class ToStringConverter : JsonConverter { public override bool CanConvert(Type objectType) { //注意:此处为待转换的类型,return true 不好用,必须将待转换的类型一一列出 return typeof(int).IsAssignableFrom(objectType) || typeof(double).IsAssignableFrom(objectType) || typeof(decimal).IsAssignableFrom(objectType); } 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) { if (value == null) { writer.WriteValue(value); } else { writer.WriteValue(value.ToString()); } } } }
2、用法
using Newtonsoft.Json;
private void button4_Click(object sender, EventArgs e) { TestParam param = new TestParam(); param.Name = "kkkkk"; param.Value = 33333; string p = JsonConvert.SerializeObject(param, new ToStringConverter()); textBox4.Text = p; }
3、测试类声明
public class TestParam { public string Name { get; set; } public decimal Value { get; set; } }
4、运行结果