2017-10-12 46 views
-1

我要让JSON这样Json.net序列C#

{ 
     'month': '201701', 
     'value': '170', 
     'target': '100' 
    }, 
    { 
     'month': '201702', 
     'value': '200', 
     'target': '200' 
    }, 
    { 
     'month': '201703', 
     'value': '210', 
     'target': '400' 
    } 

在牛顿文档是这样https://www.newtonsoft.com/json/help/html/SerializeObject.htm

我下面的文件,但只得到

{ 
    'month': '201701', 
    'value': '170', 
    'target': '100' 
} 

和我尝试像这样插入我的循环中

SellTrhu product = new SellTrhu(); 
      for (int i = 1; i <= 8; i++) 
      { 
       double[] month = new double[8]; 
       month[i] = 201700 + i; 
       amount[i] = _context.VGetSellThruSales.Where(y => y.Month == month[i]).Select(x => x.NetAmount ?? 0).Sum(); 
       targetAmount[i] = _context.DashboardSellThruSummary.Where(y => y.Month == month[i]).Select(x => x.Ach ?? 0).Sum(); 

       product.month = month[i]; 
       product.value = amount[i]; 
       product.target = targetAmount[i]; 
      } 

但它返回错误

+0

ü没有将其添加到列表中。它应该是一个项目的集合。您需要序列化的产品集合。现在,您可能会序列化一个对象。您应该将产品包含在for循环中。然后将产品添加到产品列表中,然后序列化 –

+0

帖子中的示例输出不代表有效的JSON,因此您需要使用各个块的字符串连接手动构建它... C#示例非常奇怪,并且不会澄清问题。 .. –

+0

你会得到什么错误?另外我注意到你没有初始化金额和targetAmount。另一个问题是,您的产品变量会针对每个循环迭代继续被覆盖。 –

回答

1

我认为这是你想要的。

 List<SellTrhu> products = new List<SellTrhu>(); 
     for (int i = 1; i <= 8; i++) 
     { 
      SellTrhu product = new SellTrhu(); 
      double[] month = new double[8]; 
      month[i] = 201700 + i; 
      amount[i] = _context.VGetSellThruSales.Where(y => y.Month == month[i]).Select(x => x.NetAmount ?? 0).Sum(); 
      targetAmount[i] = _context.DashboardSellThruSummary.Where(y => y.Month == month[i]).Select(x => x.Ach ?? 0).Sum(); 

      product.month = month[i]; 
      product.value = amount[i]; 
      product.target = targetAmount[i]; 
      products.Add(product); 
     } 

现在序列化产品