这里以最多保留三位小数为例:
using Newtonsoft.Json;
using System;
public class JsonTool
{
public static string ToJson(object obj)
{
JsonSerializerSettings settings = new()
{
TypeNameHandling = TypeNameHandling.Auto,
ReferenceLoopHandling = ReferenceLoopHandling.Error
};
settings.Converters.Add(new FloatJsonConerter(3));
return JsonConvert.SerializeObject(obj, settings);
}
public static T FromJson<T>(string json)
{
json ??= "";
JsonSerializerSettings settings = new()
{
TypeNameHandling = TypeNameHandling.Auto,
ReferenceLoopHandling = ReferenceLoopHandling.Error
};
return JsonConvert.DeserializeObject<T>(json, settings);
}
public class FloatJsonConerter : JsonConverter
{
int floatPlaces = 0;
public FloatJsonConerter(int floatPlaces = 0) { this.floatPlaces = floatPlaces; }
public override bool CanConvert(Type objectType)
{
return objectType == typeof(float);
}
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 is float floatValue)
{
float roundedValue = (float)Math.Round(floatValue, floatPlaces);
writer.WriteValue(roundedValue);
}
}
}
}