如何在json FROM SQL中创建数组标题?

时间:2017-03-10 10:11:37

标签: c# json

目前,我的结果是这样的:

[    
      {  
         "ib_itemcode1":"0 ",
         "transtatuscode":"IN",
         "invtid":"02007997 ",
         "descr":"Pantene C/C Intensive Care Mask 6 x 150m "
      },
      {  
         "ib_itemcode1":"12 ",
         "transtatuscode":"12",
         "invtid":"12 ",
         "descr":"12 "
      },
      {  
         "ib_itemcode1":"1232131 ",
         "transtatuscode":"ss",
         "invtid":"123123 ",
         "descr":"qweqweqwe "
      },
      {  
         "ib_itemcode1":"13 ",
         "transtatuscode":"13",
         "invtid":"13 ",
         "descr":"13 "
      },
      {  
         "ib_itemcode1":"47400179172 ",
         "transtatuscode":"IN",
         "invtid":"13101336 ",
         "descr":"Gillette Mach 3 Dispenser 8S (X12) "
      },
      {  
         "ib_itemcode1":"47400179349 ",
         "transtatuscode":"IN",
         "invtid":"13101473 ",
         "descr":"Gillette Mach3 Cart 4S (X12) "
      }
]

如何设置产品标题,使其看起来像这样

[  
 "Product":[
   {  
      "ib_itemcode1":"0 ",
      "transtatuscode":"IN",
      "invtid":"02007997 ",
      "descr":"Pantene C/C Intensive Care Mask 6 x 150m "
   },
   {  
      "ib_itemcode1":"12 ",
      "transtatuscode":"12",
      "invtid":"12 ",
      "descr":"12 "
   },
   {  
      "ib_itemcode1":"1232131 ",
      "transtatuscode":"ss",
      "invtid":"123123 ",
      "descr":"qweqweqwe "
   },
   {  
      "ib_itemcode1":"13 ",
      "transtatuscode":"13",
      "invtid":"13 ",
      "descr":"13 "
   },
   {  
      "ib_itemcode1":"47400179172 ",
      "transtatuscode":"IN",
      "invtid":"13101336 ",
      "descr":"Gillette Mach 3 Dispenser 8S (X12) "
   },
   {  
      "ib_itemcode1":"47400179349 ",
      "transtatuscode":"IN",
      "invtid":"13101473 ",
      "descr":"Gillette Mach3 Cart 4S (X12) "
   }
           ]
]

我提取所有这些的方式来自SQL服务器。

我在视觉工作室的解决方案中有两个项目。

  1. ProductDataAccess(数据库)

  2. ProcuctServiceFinal(创建Rest服务的代码)

  3. 在(1)

    namespace ProductDataAccess
    {
    using System;
    using System.Collections.Generic;
    
    public partial class product
    {
        public string ib_itemcode1 { get; set; }
        public string transtatuscode { get; set; }
        public string invtid { get; set; }
        public string descr { get; set; }
    }
    }
    

    我应该去哪里或如何添加标题?

1 个答案:

答案 0 :(得分:2)

第一个输出不正确JSON,因为数组没有属性。您可能需要{ "Product": [...] }而不是[ "Product": [...] ]。使用花括号而不是方括号,它是此类对象的序列化输出:

class MyJsonClass {
    public product[] Product { get; set; }
}

你会像这样实例化(假设你有product1product6的变量和所需的内容):

MyJsonClass itemToSerialize = new MyJsonClass() {
    Product = { product1, product2, product3, product4, product5, product6 }
};

如果你想要输出像你的第二个exaple那样你需要序列化一个product的数组:

product[] itemToSerialize = { product1, product2, product3, product4, product5, product6 };