Newtonsoft.Json
Newtonsoft.Json copied to clipboard
User-defined conversion operator is not called when the source string is the empty string
Destination type
public class MessageTemplate : IWeighted
{
public const double DefaultWeight = 1.0d;
public MessageTemplate()
{
}
public MessageTemplate(string text)
{
Text = text;
}
public MessageTemplate(string text, double weight)
{
Text = text;
Weight = weight;
}
public string Text { get; set; }
[DefaultValue(DefaultWeight)]
public double Weight { get; set; } = DefaultWeight;
public static implicit operator MessageTemplate(string value)
{
return new MessageTemplate(value);
}
public override string ToString()
{
return Text;
}
Source JSON
[ "Value", "" ]
Steps to reproduce
const string json = "[\"Value\", \"\"]";
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<MessageTemplate[]>(json);
Assert.AreEqual("Value", result[0].Text);
Assert.IsNotNull(result[1]); // AssertFailedException: 'Assert.IsNotNull failed. '
Expected behavior
Deserializing a JSON string to a type with a string conversion operator calls the operator with the JSON string, even if it represents the empty string.
Actual behavior
Deserializing a JSON string to a type with a string conversion operator calls the operator with the JSON string, unless the JSON string represents the empty string; then it does not call the conversion operator and instead returns null
.
Ran into same issue. Took some time to identify the problem. Can this be fixed?