C#JsonSerialize没有成员名称

时间:2011-05-17 16:33:24

标签: c# json serialization

我有以下类,我喜欢序列化到Json。我现在正在得到这样的东西

 var pgdata =   {"SeriesList":[{"label":"Fund","data":[{"Year":2000,"RateOfReturn":0.02},{"Year":2009,"RateOfReturn":0.03}]},{"label":"Benchmark","data":[{"Year":2000,"RateOfReturn":0.024},{"Year":2009,"RateOfReturn":0.032}]}]} ;

我喜欢这样的东西

var pgdata =   {"SeriesList":[{"label":"Fund","data":[[2000,0.02],[2009,0.03]]},{"label":"Benchmark","data":[[2000,0.024],[2009,0.032]]}]} ;

C#代码:

public class JsonPerformGraphData
    {
        public List<Series> SeriesList = new List<Series>();

        public Series GetSeries(string name)
        {
            foreach (Series s in SeriesList)
            {
                if (s.label == name)
                    return s;
            }

            Series series = new Series(name);
            SeriesList.Add(series);
            return series;
        }

        public void Add(PerformanceGraphItem ppgi)
        {
            Series s = GetSeries(ppgi.PerformanceGraphSeries.Name);
            s.addItem(ppgi.Year, ppgi.RateOfReturn);
        }


        public class Series
        {
            public string label;
            public List<Data> data = new List<Data>();

            public Series(String name)
            {
                label = name;
            }

            public void addItem(short year, double rateOfReturn)
            {

                data.Add(new Data(year,rateOfReturn));

            }
        }

        public class Data
        {
            public short Year;
            public double RateOfReturn;

            public Data(short year, double rateOfReturn)
            {
                Year = year;
                RateOfReturn = rateOfReturn;
            }
        }

    }

1 个答案:

答案 0 :(得分:1)

您是否有使用json.NET的特殊原因?它已经解决了C#开发人员的序列化问题,并且没有理由不使用它。我遇到的唯一问题与它在JSON反序列化中使用接口对象的不灵活性有关,但除非你在这个类上进行单元测试,这不应该是一个问题(它看起来不像你)。 / p>

出于您的目的,json.NET应该为您提供您正在寻找的输出,而不必单独使用滚动序列化器。

编辑:另外,为了清楚起见,json.NET确实支持在没有成员名称的情况下按照您想要的方式进行序列化。只需为每个成员添加JsonProperty Attribute