日期:2014-05-17  浏览次数:20703 次

序列化为json
有一些int类型的数据 个数未知 ,如下面的 3  4
现在需要转成json 这个格式的//{"orderitems":[{"id":3},{"id":4}],"optype":5}            
 我这种形式对吗?string strJson = JsonConvert.SerializeObject(new { orderitems = list, optype = type }); 
如果对的话 请问list这个怎么写呢?

------解决方案--------------------
引用Newtonsoft.Json.dll。下载地址:http://download.csdn.net/detail/guwei4037/5853053
class Program
    {
        static void Main(string[] args)
        {
            Data info = new Data(new List<InnerData>() { new InnerData(3), new InnerData(4) }, 5);

            string strJson = JsonConvert.SerializeObject(info);
            Console.WriteLine(strJson);
        }
    }

    public class Data
    {
        public Data(List<InnerData> orderitems, int optype)
        {
            this.orderitems = orderitems;
            this.optype = optype;
        }

        public List<InnerData> orderitems { get; set; }
        public int optype { get; set; }
    }

    public class InnerData
    {
        public InnerData(int id)
        {
            this.id = id;
        }
        public int id { get; set; }
    }

效果: