JSON序列化时如何本地化?
我已经奋斗了几个小时了,但没有好的结果。我正在尝试使用 .NET JSON 序列化器将 JSON 从 UI 来回转换为对象。
小数会出现问题,因为我的文化标准使用“,”作为小数分隔符而不是“.”。我尝试实现自定义转换器(请参阅这个问题),但没有取得好的结果。
我还检查了 NewtonSoft JSON.net,但没有更好的结果。到目前为止,与值类型的匹配似乎是文化不变的。我想覆盖这种行为,该怎么做?
顺便说一句,我真的希望避免在 javascript 端进行本地化。我绝对希望 .NET 能够处理跨文化格式化和本地化,我认为不应该有像我在这个序列化器中发现的例外情况,我的猜测是应该有一个正确的方法来做到这一点。
提前致谢。
I've been struggling for a few hours now with no good result. I'm trying to use .NET JSON Serializers for converting JSON back and forth from the UI into objects.
The problem arises with decimals because the standard for my culture has "," as decimal separator instead of ".". I've tried implementing a custom converter (see this question) with no good results.
I've also checked out NewtonSoft JSON.net without better results. So far it seems that matching with value types is done culture-invariantly. I want to override this behavior, how to do it?
BTW, I really wish to avoid localizing on the javascript side. I definitely want .NET to take care of cross-culture formatting and localizing, I don't think there should be exceptions like I'm finding with this serializers, my guess is that there should be a proper way to do this.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
用于序列化十进制值的 JSON 标准不提供本地化格式。 (请参阅 JSON.org。)这就是为什么值始终采用不变区域性进行格式化的原因。
如果您需要本地化值,那么您需要为您选择的序列化器创建一个自定义转换器,它将小数输出为预格式化字符串。在 Json.Net 中,这可以很容易地完成,如下所示:
输出:
The JSON standard for serializing decimal values does not provide for localized formatting. (See JSON.org.) This is why values are always formatted with the Invariant culture.
If you need localized values, then you'll need to create a custom converter for your serializer of choice which outputs the decimals as pre-formatted strings instead. In Json.Net, this can be done easily as shown below:
Output:
您是否在当前线程的 CurrentCulture 和 CurrentUICulture 属性上设置了正确的 CultureInfo ?
Are you setting proper CultureInfo on your current thread's CurrentCulture and CurrentUICulture properties?