JsonSerializer - serialize decimal places with 'N2' formatting - asp.net-mvc

I'm serializing decimals using Newtonsoft.Json.JsonSerializer.
How can I set it to serialize decimal numbers with only 1 decimal place to use 0 at the end.
i.e. 3.5 serializes to "3.50"?

You'll have to write your own custom JsonConverter and use it to intercept the decimal type so you can change how it gets serialized. Here's an example:
public class DecimalFormatConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(decimal));
}
public override void WriteJson(JsonWriter writer, object value,
JsonSerializer serializer)
{
writer.WriteValue(string.Format("{0:N2}", value));
}
public override bool CanRead
{
get { return false; }
}
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
To use it, simply pass in a new instance of this custom converter to the SerializeObject method:
var json = JsonConvert.SerializeObject(yourObject, new DecimalFormatConverter());

The accepted answer is correct, but expanding upon the comments on accepted answer:
If you want the decimals in your JSON to be numbers instead of strings, you need to use WriteRawValue and use :0.00 instead of :N2 for the string formatting (as N2 includes thousand separator commas and other culture specific number formatting that will break your JSON)
public class DecimalFormatConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(decimal);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteRawValue($"{value:0.00}");
}
public override bool CanRead => false;
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
This is the difference in output compared to the accepted answer.
# writer.WriteRawValue($"{value:0.00}");
{
"MyDecimal": 3.50,
"MyBiggerDecimal": 12345.50
}
# writer.WriteValue($"{value:N2}");
{
"MyDecimal": "3.50",
"MyBiggerDecimal": "12,345.50"
}
Note - the accepted answer is correct for the OP's specific question i.e. serialize 3.5 to "3.50", but I got here wanting to serialize 3.5 to 3.50 (without the string quotes).

Hy!
The second answer is also correct, but not reflecting Cultures.
If you want to have really 0.00 (with .) you have to use:
public class DecimalFormatConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(decimal);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
FormattableString formattableString = $"{value:0.00}";
writer.WriteRawValue(formattableString.ToString(CultureInfo.InvariantCulture));
}
public override bool CanRead => false;
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
With this it is garantueed to have dot as decimal separater.
The difference is:
FormattableString formattableString = $"{value:0.00}";
writer.WriteRawValue(formattableString.ToString(CultureInfo.InvariantCulture));

Related

How to modify binded value in MVVM Cross

I have a model from my json in a Xamarin MVVM app(ios). I want to add the "%" after the value? in the list "coinmarketcaplist" contains the value 24h_change, this is the value I want to add a % to, it's a string. I know that I should use a getter for it, but I don't know how since I'm fairly new to this. below is my ViewModel code:
public class CMCTableViewModel : MvxViewModel
{
protected readonly ICoinMarketCapService _coinMarketCapService;
public CMCTableViewModel(ICoinMarketCapService coinMarketCapService)
{
_coinMarketCapService = coinMarketCapService;
LoadData();
}
private List<CoinMarketCapModel> _coinMarketCapModelList;
public List<CoinMarketCapModel> CoinMarketCapModelList
{
get
{
return _coinMarketCapModelList;
}
set
{
_coinMarketCapModelList = value;
RaisePropertyChanged(() => CoinMarketCapModelList);
}
}
public async void LoadData()
{
CoinMarketCapModelList = await _coinMarketCapService.GetCoins();
}
}
TableCell:
internal static readonly NSString Identifier = new NSString("CMCTableCell");
public override void LayoutSubviews()
{
base.LayoutSubviews();
MvxFluentBindingDescriptionSet<CMCTableCell, CoinMarketCapModel> set = new MvxFluentBindingDescriptionSet<CMCTableCell, CoinMarketCapModel>(this);
set.Bind(lblName).To(res => res.Name);
set.Bind(lblPrice).To(res => res.percent_change_24h);
set.Bind(imgCoin)
.For(img => img.Image)
.To(res => res.image)
.WithConversion<StringToImageConverter>();
set.Apply();
}
}
edit: added cellview
Use a converter in your binding:
1) Define converter:
public class StringFormatValueConverter : MvxValueConverter
{
public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return null;
if (parameter == null)
return value;
return string.Format(parameter.ToString(), value);
}
}
2) Use it in your binding:
set.Bind(lblPrice).To(res => res.percent_change_24h).WithConversion<StringFormatValueConverter>("{0} %");
You can use this converter when you want to modify the input string by adding something around it, for example unit or currency

Allow empty string for EmailAddressAttribute

I have property in my PersonDTO class:
[EmailAddress]
public string Email { get; set; }
It works fine, except I want to allow empty strings as values for my model, if I send JSON from client side:
{ Email: "" }
I got 400 bad request response and
{"$id":"1","Message":"The Email field is not a valid e-mail address."}
However, it allows omitting email value:
{ FirstName: "First", LastName: 'Last' }
I also tried:
[DataType(DataType.EmailAddress, ErrorMessage = "Email address is not valid")]
but it does not work.
As far as I understood, Data Annotations Extensions pack does not allow empty string either.
Thus, I wonder if there is a way to customize the standard EmailAddressAttribute to allow empty strings so I do not have to write custom validation attribute.
You have two options:
Convert string.Empty to null on the Email field. Many times that is perfectly acceptable. You can make this work globally, or by simply making your setter convert string.Empty to null on the email field.
Write a custom EmailAddress attribute, since EmailAddressAttribute is sealed you can wrap it and write your own forwarding IsValid method.
Sample:
bool IsValid(object value)
{
if (value == string.Empty)
{
return true;
}
else
{
return _wrappedAttribute.IsValid(value);
}
}
Expansion on option 1 (from Web Api not converting json empty strings values to null)
Add this converter:
public class EmptyToNullConverter : JsonConverter
{
private JsonSerializer _stringSerializer = new JsonSerializer();
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
string value = _stringSerializer.Deserialize<string>(reader);
if (string.IsNullOrEmpty(value))
{
value = null;
}
return value;
}
public override void WriteJson(JsonWriter writer, object value,
JsonSerializer serializer)
{
_stringSerializer.Serialize(writer, value);
}
}
and use on the property:
[JsonConverter(typeof(EmptyToNullConverter))]
public string EmailAddress {get; set; }
or globally in WebApiConfig.cs:
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
new EmptyToNullConverter());
It's Easy. Do This. Bye
private string _Email;
[EmailAddress(ErrorMessage = "Ingrese un formato de email válido")]
public string Email { get { return _Email; } set { _Email = string.IsNullOrWhiteSpace(value) ? null : value; } }
I used the suggestion from Yishai Galatzer to make a new ValidationAttribute called EmailAddressThatAllowsBlanks:
namespace System.ComponentModel.DataAnnotations
{
public class EmailAddressThatAllowsBlanks : ValidationAttribute
{
public const string DefaultErrorMessage = "{0} must be a valid email address";
private EmailAddressAttribute _validator = new EmailAddressAttribute();
public EmailAddressThatAllowsBlanks() : base(DefaultErrorMessage)
{
}
public override bool IsValid(object value)
{
if (string.IsNullOrEmpty(value.ToString()))
return true;
return _validator.IsValid(value.ToString());
}
}
}
Set TargetNullValue property of the binding to an empty string.
TargetNullValue=''

Serialize IList property on model when passed into Html.ActionLink

I'm trying to generate an Html.ActionLink with the following viewmodel:
public class SearchModel
{
public string KeyWords {get;set;}
public IList<string> Categories {get;set;}
}
To generate my link I use the following call:
#Html.ActionLink("Index", "Search", Model)
Where Model is an instance of the SearchModel
The link generated is something like this:
http://www.test.com/search/index?keywords=bla&categories=System.Collections.Generic.List
Because it obviously is only calling the ToString method on every property.
What I would like to see generate is this:
http://www.test.com/search/index?keywords=bla&categories=Cat1&categories=Cat2
Is there any way I can achieve this by using Html.ActionLink
In MVC 3 you're just out of luck because the route values are stored in a RouteValueDictionary that as the name implies uses a Dictionary internally which makes it not possible to have multiple values associated to a single key. The route values should probably be stored in a NameValueCollection to support the same behavior as the query string.
However, if you can impose some constraints on the categories names and you're able to support a query string in the format:
http://www.test.com/search/index?keywords=bla&categories=Cat1|Cat2
then you could theoretically plug it into Html.ActionLink since MVC uses TypeDescriptor which in turn is extensible at runtime. The following code is presented to demonstrate it's possible, but I would not recommend it to be used, at least without further refactoring.
Having said that, you would need to start by associating a custom type description provider:
[TypeDescriptionProvider(typeof(SearchModelTypeDescriptionProvider))]
public class SearchModel
{
public string KeyWords { get; set; }
public IList<string> Categories { get; set; }
}
The implementation for the provider and the custom descriptor that overrides the property descriptor for the Categories property:
class SearchModelTypeDescriptionProvider : TypeDescriptionProvider
{
public override ICustomTypeDescriptor GetTypeDescriptor(
Type objectType, object instance)
{
var searchModel = instance as SearchModel;
if (searchModel != null)
{
var properties = new List<PropertyDescriptor>();
properties.Add(TypeDescriptor.CreateProperty(
objectType, "KeyWords", typeof(string)));
properties.Add(new ListPropertyDescriptor("Categories"));
return new SearchModelTypeDescriptor(properties.ToArray());
}
return base.GetTypeDescriptor(objectType, instance);
}
}
class SearchModelTypeDescriptor : CustomTypeDescriptor
{
public SearchModelTypeDescriptor(PropertyDescriptor[] properties)
{
this.Properties = properties;
}
public PropertyDescriptor[] Properties { get; set; }
public override PropertyDescriptorCollection GetProperties()
{
return new PropertyDescriptorCollection(this.Properties);
}
}
Then we would need the custom property descriptor to be able to return a custom value in GetValue which is called internally by MVC:
class ListPropertyDescriptor : PropertyDescriptor
{
public ListPropertyDescriptor(string name)
: base(name, new Attribute[] { }) { }
public override bool CanResetValue(object component)
{
return false;
}
public override Type ComponentType
{
get { throw new NotImplementedException(); }
}
public override object GetValue(object component)
{
var property = component.GetType().GetProperty(this.Name);
var list = (IList<string>)property.GetValue(component, null);
return string.Join("|", list);
}
public override bool IsReadOnly { get { return false; } }
public override Type PropertyType
{
get { throw new NotImplementedException(); }
}
public override void ResetValue(object component) { }
public override void SetValue(object component, object value) { }
public override bool ShouldSerializeValue(object component)
{
throw new NotImplementedException();
}
}
And finally to prove that it works a sample application that mimics the MVC route values creation:
static void Main(string[] args)
{
var model = new SearchModel { KeyWords = "overengineering" };
model.Categories = new List<string> { "1", "2", "3" };
var properties = TypeDescriptor.GetProperties(model);
var dictionary = new Dictionary<string, object>();
foreach (PropertyDescriptor p in properties)
{
dictionary.Add(p.Name, p.GetValue(model));
}
// Prints: KeyWords, Categories
Console.WriteLine(string.Join(", ", dictionary.Keys));
// Prints: overengineering, 1|2|3
Console.WriteLine(string.Join(", ", dictionary.Values));
}
Damn, this is probably the longest answer I ever give here at SO.
with linq of course...
string.Join("", Model.Categories.Select(c=>"&categories="+c))

Castle Windsor Typed Factory Facility with generics

I'm trying to register a factory that could resolve an array of event handlers defined as follow:
public interface IEvent { }
public class EventA : IEvent { }
public class EventB : IEvent { }
public class EventC : IEvent { }
public interface IHandler<TEvent> where TEvent : IEvent
{
void Handle(TEvent ev);
}
public class HandlerX : IHandler<EventA>, IHandler<EventB>
{
public void Handle(EventA ev)
{
throw new NotImplementedException("handle EventA");
}
public void Handle(EventB ev)
{
throw new NotImplementedException("handle EventB");
}
}
public class HandlerY : IHandler<EventB>, IHandler<EventC>
{
public void Handle(EventB ev)
{
throw new NotImplementedException("handle EventB");
}
public void Handle(EventC ev)
{
throw new NotImplementedException("handle EventC");
}
}
public interface HandlerFactory
{
object[] GetHandlersForEvent(IEvent ev);
}
Basically for each event I can have more handlers and each handler can handle multiple events. I also want the factory to return object[] because at runtime I don't know what closed generic types would be returned.
I tried the approach descirbed by Krzysztof Koźmic http://kozmic.pl/2010/03/11/advanced-castle-windsor-ndash-generic-typed-factories-auto-release-and-more/
but still have problems.
Basically my question boils down to what types to return from my custom type deriving from DefaultTypedFactoryComponentSelector.
I tried many variations of the following:
public class HandlerSelector : DefaultTypedFactoryComponentSelector
{
protected override TypedFactoryComponent BuildFactoryComponent(MethodInfo method, string componentName, Type componentType, System.Collections.IDictionary additionalArguments)
{
Type eventType = null;
foreach (var k in additionalArguments.Values)
{
eventType = k.GetType();
}
var handlerType = typeof(IHandler<>).MakeGenericType(eventType);
var handlerArrayType = handlerType.MakeArrayType();
//return handlerArrayType;
return new TypedFactoryComponentCollection(handlerType, additionalArguments);
}
protected override Type GetComponentType(MethodInfo method, object[] arguments)
{
return typeof (object);
/*
var message = arguments[0];
var handlerType = typeof(IHandler<>).MakeGenericType(message.GetType());
var handlerArrayType = handlerType.MakeArrayType();
return handlerArrayType;
*/
}
/*
public TypedFactoryComponent SelectComponent(MethodInfo method, Type type, object[] arguments)
{
var message = arguments[0];
var handlerType = typeof(IHandler<>).MakeGenericType(message.GetType());
var result = new TypedFactoryComponentCollection(handlerType.MakeArrayType(), new Arguments(arguments));
return result;
}*/
}
with Windsor installer defined as:
public class Installer : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.AddFacility<TypedFactoryFacility>()
.Register(
Component.For<HandlerSelector>().ImplementedBy<HandlerSelector>(),
Component.For<AutoReleaseHandlerInterceptor>(),
AllTypes.FromAssemblyContaining<Program>()
.BasedOn(typeof(IHandler<>))
.WithService.Base()
.Configure(c => c.LifeStyle.Is(LifestyleType.Transient)
.Interceptors<AutoReleaseHandlerInterceptor>()),
Component.For<HandlerFactory>().AsFactory(c => c.SelectedWith<HandlerSelector>()));
}
}
When calling factory.GetHandlersForEvent(ev); I get an exception complaining about array type mismatch:
"Attempted to access an element as a type incompatible with the array."
Stack trace:
at System.Collections.Generic.Dictionary2.ValueCollection.CopyTo(TValue[] array, Int32 index)
at System.Collections.Generic.Dictionary2.ValueCollection.System.Collections.ICollection.CopyTo(Array array, Int32 index)
at Castle.MicroKernel.DefaultKernel.ResolveAll(Type service, IDictionary arguments) in e:\OSS.Code\Castle.Windsor\src\Castle.Windsor\MicroKernel\DefaultKernel_Resolve.cs:line 285
at Castle.Facilities.TypedFactory.TypedFactoryComponentCollection.Resolve(IKernel kernel) in e:\OSS.Code\Castle.Windsor\src\Castle.Windsor\Facilities\TypedFactory\TypedFactoryComponentCollection.cs:line 39
at Castle.Facilities.TypedFactory.Internal.TypedFactoryInterceptor.Resolve(IInvocation invocation) in e:\OSS.Code\Castle.Windsor\src\Castle.Windsor\Facilities\TypedFactory\Internal\TypedFactoryInterceptor.cs:line 173
at Castle.Facilities.TypedFactory.Internal.TypedFactoryInterceptor.Intercept(IInvocation invocation) in e:\OSS.Code\Castle.Windsor\src\Castle.Windsor\Facilities\TypedFactory\Internal\TypedFactoryInterceptor.cs:line 83
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.HandlerFactoryProxy.GetHandlersForEvent(IEvent ev)
at CastleWindsorTests.Program.TryIt(HandlerFactory factory) in c:\users\user\documents\visual studio 2010\Projects
How to implement the HandlerSelector so that it works well with factory defined as returning object[] whereas the real objects at runtime are closed generic types?
I'll be happy to be pointed to some existing documentation with guidelines for implementors of ITypedFactoryComponentSelector / DefaultTypedFactoryComponentSelector. Yes, I tried the http://docs.castleproject.org/(S(kwaa14uzdj55gv55dzgf0vui))/Windsor.Typed-Factory-Facility-interface-based-factories.ashx but here's not much about the above types.
I really don't want to introduce a service locator (instead of factory) ;).
To answer my own question:
I must've been blind. After reading more closely the xmldoc of the methods I override, changing HandlerSelector to the following solved the problem:
public class HandlerSelector : DefaultTypedFactoryComponentSelector
{
protected override TypedFactoryComponent BuildFactoryComponent(MethodInfo method, string componentName, Type componentType, System.Collections.IDictionary additionalArguments)
{
return new TypedFactoryComponentCollection(componentType, additionalArguments);
}
protected override Type GetComponentType(MethodInfo method, object[] arguments)
{
var message = arguments[0];
var handlerType = typeof(IHandler<>).MakeGenericType(message.GetType());
return handlerType;
}
}
#workabyte
For Castle v3, GetComponentType method stays the same but the BuildFactoryComponent method looks like this for me:
protected override Func<IKernelInternal, IReleasePolicy, object> BuildFactoryComponent(MethodInfo method, string componentName, Type componentType, IDictionary additionalArguments)
{
return (kernel, rp) => kernel.ResolveAll(componentType);
}

ModelMetadata: ShowForEdit property not appearing to work

Iv wrote an MetaDataProvider like the one below and am using it in conjunction with Editor templates. The DisplayName is working correctly, but for some reason the ShowForEdit value it not having any effect. Any ideas?
public class MyModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType,
Func<object> modelAccessor, Type modelType, string propertyName)
{
var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName); I
metadata.DisplayName = "test";
metadata.ShowForEdit = false;
metadata.ShowForDisplay = false;
metadata.HideSurroundingHtml = true;
return metadata;
}
}
This seems similar to the question Why can't I set ShowForEdit model metadata with an attribute?, so I'll replicate my answer here:
What is the type of property you are applying it to? If we use Reflector, we can discover that the ShowForEdit and ShowForDisplay properties are used in the following functions:
ShowForEdit: System.Web.Mvc.Html.DefaultEditorTemplates.ShouldShow(...)
ShowForDisplay: System.Web.Mvc.Html.DefaultDisplayTemplates.ShouldShow(...)
The definition of those methods is:
private static bool ShouldShow(ModelMetadata metadata, TemplateInfo templateInfo)
{
return (((metadata.ShowForEdit && (metadata.ModelType != typeof(EntityState))) && !metadata.IsComplexType) && !templateInfo.Visited(metadata));
}
private static bool ShouldShow(ModelMetadata metadata, TemplateInfo templateInfo)
{
return (((metadata.ShowForDisplay && (metadata.ModelType != typeof(EntityState))) && !metadata.IsComplexType) && !templateInfo.Visited(metadata));
}
Ignoring the obvious property check (metadata.ShowForX), you can see that it is checking whether the model is an intstance of EntityState (probably isn't), and then a check for metadata.IsComplexType.
We can look at the IsComplexType property here:
public virtual bool IsComplexType
{
get
{
return !TypeDescriptor.GetConverter(this.ModelType).CanConvertFrom(typeof(string));
}
}
What that is saying is that it will return true if the model cannot be converted from a string, and in the ShouldShow() methods, it will show if it is not a complex type, i.e., the value CAN be converted from a string.
What you will need to do, is create a TypeConverter that can convert a string, to the model, e.g:
A model:
[TypeConverter(typeof(ItemConverter))]
public class Item
{
#region Properties
public string Text { get; set; }
#endregion
}
And a converter:
public class ItemConverter : TypeConverter
{
#region Methods
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value.GetType() == typeof(string))
{
return new Item { Text = (string)value };
}
return base.ConvertFrom(context, culture, value);
}
#endregion
}
With that in place, try it again and see if that helps.

Resources