簡體   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