c#WebApi十进制序列化

时间:2016-07-11 18:03:36

标签: c# json serialization asp.net-web-api decimal

我有一个返回List的WebApi Controller。我的问题是,我不希望在生成的JSON中使用xxxx.0,因为这会在我的javascript中造成严重问题。有没有办法防止.net值的.net序列化,以便它们被截断?

当前输出:

{"Temperature":[[1465434000.0,4.00],[1465437600.0,15.40],[1465441200.0,15.26],

通缉:

{"Temperature":[[1465434000,4.00],[1465437600,15.40],[1465441200,15.26],

序列化的对象:

public class ChartDataMonthly
{
    public List<decimal[]> Temperature { get; set; }

3 个答案:

答案 0 :(得分:0)

我想我要开始在你的对象上为你的javascript模型创建一个新属性:

public class ChartDataMonthly
{
    public List<decimal[]> Temperature { get; set; }

    // This can be "unmapped" to ignore object mappers
    public List<string> RoundedTemperature 
    { 
        get
        {
            return Temperature.Select(t => Math.Round(t).ToString()).ToList();
        }
    }
    // rest of model
}

答案 1 :(得分:0)

public class ChartDataMonthly
{
    public List<decimal[]> Temperature { get; set; }

    public List<decimal[]> Round()
    {
        List<decimal[]> NewTemp = new List<decimal[]>();
        foreach(var t in Temperature)
        {
           t[0] = Math.Round(t[0], 0);
           NewTemp.Add(t)
        }

        return NewTemp;
    }
}

我看到一个类似于这个的新答案在我的前两分钟发布,但这大致是我的开始。您可以使用返回List或Json.SerializeObject并通过稍微修改方法返回字符串以返回类似于@ dckuehn的答案的字符串。

答案 2 :(得分:0)

    public class ChartDataMonthly
    {
        public List<decimal[]> _temperature;
        public List<decimal[]> Temperature
        {
            get { return _temperature; }
            set
            {
                _temperature = value;
                //edit each value by reference
                _temperature.ForEach(x => x.ToList().ForEach(y =>y= Convert.ToDecimal(Math.Round(Convert.ToDouble(y)))));
            }
        }
    }

Untested but i think it should do the work automatically You just round every field of each array in your list.

If you do it inside a setter/getter it will automatically do it when the .net binder bind the JavaScript to your object