I have a custom JSON converter for a class that has several fields of various types, I have an specific rules to map negative double fields to null, but I want that rule applied based upon field name, ie:
I have class
public class sampleClass
{
public double x { get; set; }
public double y { get; set; }
public double z { get; set; }
public double w { get; set; }
}
when converting the class with the following values
sampleClass c = new sampleClass()
{
x = -1,
y = 2,
z = -1,
w = 8
};
Result would be:
{
"x": null,
"y": "2",
"z": null,
"w": "8"
}
but I'd like it to be:
{
"x": null,
"y": "2",
"z": "-1",
"w": "8"
}
That is, custom converter would apply override conversion to x but not to z based on the field name, but neither CanConvert nor WriteJson receives information about field name
Any ideas regarding this problem will be apreciated
Below I pasted the code for the custom decimal converter (name can be different) that I'm currently using
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);
}
}