简体   繁体   中英

Serialize a decimal to a human readable currency format

I am using json.net library to serialize an object which has a decimal value that represents a cost. When serializing, I want the json to look something like '$400,000' instead of '400000.0' .

Is there a way that I can accomplish this in an easy and efficient way? This object contains many other secondary objects and subsequent properties.

The application will be used locally and the specs say that the output should be in human readable format. Culture variance isn't of any importance in this context.

There's no easy way to perform this since you can't work around a fact that serializer is directly accessing your properties.

If you need a formatted JSON output I would recommend writing a helper class that wraps the class you want to expose. Unfortunately I've done this once for some XML report and really the easiest way went something like this:

class PersonXml
{
   Person _person;

   void PersonXml(Person person) { _person = person; }

   string Age { get { return _person.Age + " years"; } }
}

This is just a simple example I wrote on the fly but the principle is always the same. Even if some advanced JSON serializer offered me ways to format my output, I'd really keep this concept out of my main objects in a separate file with separate helper classes.

Again this isn't quite the solution, in my opinion it should never come to this but if it does, this is the lesser of the evils in my experience.

Also, just note that if you reference the class in your property getters there's a danger of null reference.

正如D Stanley所建议的,我将字段类型从十进制更改为字符串,因为其中的数据仅被读取而不用于数据操作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM