Here is my dto of action for json input :
public class GreetRequest
{
public string Message{get;set;}
}
When the json is post from the client:
{
"Message":true
}
the json.net would convert the Boolean to string automatically:
true -> “true”
By far,I wrote a converter to enforce the rule:
public class StrictStringConverter : JsonConverter
{
readonly JsonSerializer defaultSerializer = new JsonSerializer();
public override bool CanConvert(Type objectType)
{
return objectType.IsStringType();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
switch (reader.TokenType)
{
case JsonToken.String:
case JsonToken.Null:
return defaultSerializer.Deserialize(reader, objectType);
default:
throw new JsonSerializationException();
}
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public static class JsonExtensions
{
public static bool IsStringType(this Type type)
{
type = Nullable.GetUnderlyingType(type) ?? type;
if (type == typeof(string))
return true;
return false;
}
}
the converter is configure at startup.cs
services.Configure<MvcNewtonsoftJsonOptions>(options => {
options.SerializerSettings.Converters.Add(new StrictStringConverter());
});
Question:
- Is there any out of box way of strict conversion for json input, without writing any converter manually.