1

私はナンシーに不慣れで、次のようなNancy.ModelBinding名前空間を使用してdecimalプロパティをバインドしようとしています。

var model = this.Bind<AddPaymentModel>();

私のアプリは米国以外の文化(pt-BR)を使用しており、小数の表現が異なり(4.50は4,50になります)、CurrentCultureがpt-BRに正しく設定されていても、上記のコードはエラーをスローします。JSONを投稿していますが、JSONデシリアライザーに関連している可能性があります...

私のスタックトレースの一部:

Nancy.RequestExecutionException: Oh noes! ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Exception: 450,00 is not a valid value for Decimal. ---> System.FormatException: Input string was not in a correct format.
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt)
at System.Decimal.Parse(String s, NumberStyles style, IFormatProvider provider)
at System.ComponentModel.DecimalConverter.FromString(String value, NumberFormatInfo formatInfo)
at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
--- End of inner exception stack trace ---
at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
at System.ComponentModel.TypeConverter.ConvertFromInvariantString(String text)
at Nancy.Json.JavaScriptSerializer.ConvertToType(Type type, Object obj)
at Nancy.Json.JavaScriptSerializer.ConvertToObject(IDictionary`2 dict, Type type)
at Nancy.Json.JavaScriptSerializer.ConvertToType(Type type, Object obj)
at Nancy.Json.JavaScriptSerializer.ConvertToType[T](Object obj)
at Nancy.Json.JavaScriptSerializer.Deserialize[T](String input)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at Nancy.ModelBinding.DefaultBodyDeserializers.JsonBodyDeserializer.Deserialize(String contentType, Stream bodyStream, BindingContext context)
at Nancy.ModelBinding.DefaultBinder.DeserializeRequestBody(BindingContext context)
at Nancy.ModelBinding.DefaultBinder.Bind(NancyContext context, Type modelType, String[] blackList)

私は何が欠けていますか?

4

1 に答える 1

0

代わりに、ナンシーの Newtonsoft.JsonNet シリアライザーに切り替えてみてください。

http://nuget.org/packages/Nancy.Serialization.JsonNet

これが「キャッチオール」の実装例です

using System;
using System.Collections.Generic;
using Nancy;
using Nancy.Bootstrapper;
using Nancy.Serialization.JsonNet;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Application
{
    public class Bootstrapper : DefaultNancyBootstrapper
    {

        protected override NancyInternalConfiguration InternalConfiguration
        {
            get
            {
                return NancyInternalConfiguration.WithOverrides(
                c => c.Serializers.Insert(0, typeof(ModifiedJsonNetJsonSerializer)));
            }
        }

        public class ModifiedJsonNetJsonSerializer : JsonNetSerializer
        {
            public ModifiedJsonNetJsonSerializer()
                : base(new List<JsonConverter> { new FloatConverter() })
            { }

            public class FloatConverter : JsonConverter
            {
                public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
                {
                    var floatValue = (float)value;
                    writer.WriteValue(string.Format("{0:0.00}", floatValue));
                }

                public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
                {
                    var jobject = JToken.Load(reader);
                    var str = jobject.Value<string>();
                    float number;
                    try
                    {
                        number = float.Parse(str);
                    }
                    catch (FormatException)
                    {
                        str = str.IndexOf(".", StringComparison.Ordinal) > -1 ? str.Replace('.', ',') : str.Replace(',', '.');
                        number = float.Parse(str);
                    }
                    return number;
                }

                public override bool CanConvert(Type objectType)
                {
                    return objectType == typeof(float) || objectType == typeof(Single);
                }
            }
        }
    }
}
于 2012-10-28T11:08:19.457 に答える