0

我有一个自定义 JSON 转换器,用于具有多个不同类型字段的类,我有一个特定规则将负双字段映射到 null,但我希望根据字段名称应用该规则,即:

我有课

public class sampleClass
{
    public double x { get; set; }
    public double y { get; set; }
    public double z { get; set; }
    public double w { get; set; }
}

使用以下值转换类时

sampleClass c = new sampleClass()
{
    x = -1,
    y = 2,
    z = -1,
    w = 8
};

结果将是:

{
    "x": null,
    "y": "2",
    "z": null,
    "w": "8"
}

但我希望它是:

{
    "x": null,
    "y": "2",
    "z": "-1",
    "w": "8"
}

也就是说,自定义转换器将根据字段名称将覆盖转换应用于 x 而不是 z,但 CanConvert 和 WriteJson 都不会收到有关字段名称的信息

关于这个问题的任何想法都将不胜感激

下面我粘贴了我当前使用的自定义十进制转换器的代码(名称可以不同)

    class DecimalConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter jsonWriter, object inputObject, JsonSerializer jsonSerializer)
        {
            // Set the properties of the Json Writer
            jsonWriter.Formatting = Formatting.Indented;

            // Typecast the input object
            var numericObject = inputObject as double?;
            jsonWriter.WriteValue((numericObject == -1.0) ? null : numericObject);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            double? readValue = reader.ReadAsDouble();
            return (readValue == null) ? -1 : readValue;
        }

        public override bool CanConvert(Type objectType)
        {
            return (typeof(double) == objectType);
        }
    }
4

0 回答 0