繁体   English   中英

如何为子 object 序列化 json object

[英]How to serialize json object for child object

我有下面的 class 和 Header 和子 class。 我想知道如何使用 newtonsoft 对子 object 进行序列化。我在子 object 下尝试过,但它只返回一条记录,而子 object 包含 4 条记录

        public class StyleBomLeatherSetupHeader 
        {
            public int StyleStockID { get; set; }
            public List<StyleBomLeatherSetup> Details { get; set; }
    
        }
    
        public class StyleBomLeatherSetup
        {
            public int StyleBomLeatherID { get; set; }
            public int StyleStockID { get; set; }
            public int? TypeID { get; set; }
            public int? PartNoID { get; set; }
            public int? ComponentID { get; set; }
            public int? LeatherID { get; set; }
            public int? ColorID { get; set; }
            public decimal? Norms { get; set; }
    
            public decimal? Wastage { get; set; }
    
            public decimal? TotalNorms { get; set; }
        }

序列化 json object:-

     styleBomLeatherSetupHeader.StyleStockID = styleStockSetup.StyleStockID;
     styleBomLeatherSetupHeader.Details = styleBomLeatherSetups;
     protected StyleBomLeatherSetupHeader styleBomLeatherSetupHeader { get; set; } = new StyleBomLeatherSetupHeader();
        
     string json = JsonConvert.SerializeObject(styleBomLeatherSetupHeader);

设置完 header object 后,您可以使用属性“详细信息”指向子列表。 话虽如此,您可以只序列化该属性,如下所示:

string detailsJson =JsonConvert.SerializeObject(styleBomLeatherSetupHeader.Details);
    public class StyleBomLeatherSetupHeader 
    {
        public StyleBomLeatherSetupHeader ()
        {
          Details = new List<StyleBomLeatherSetup>();
        }
        public int StyleStockID { get; set; }
        public IList<StyleBomLeatherSetup> Details { get; set; }

    }

    public class StyleBomLeatherSetup
    {
        public int StyleBomLeatherID { get; set; }
        public int StyleStockID { get; set; }
        public int? TypeID { get; set; }
        public int? PartNoID { get; set; }
        public int? ComponentID { get; set; }
        public int? LeatherID { get; set; }
        public int? ColorID { get; set; }
        public decimal? Norms { get; set; }

        public decimal? Wastage { get; set; }

        public decimal? TotalNorms { get; set; }        
    }

然后

styleBomLeatherSetupHeader.StyleStockID=styleStockSetup.StyleStockID;
foreach(styleBomLeatherSetup in styleBomLeatherSetups)
{
       styleBomLeatherSetupHeader.Details.Add(new StyleBomLeatherSetup{
        // map your properties.
       });
}
    
         string json = JsonConvert.SerializeObject(styleBomLeatherSetupHeader);

   

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM