I have below class with Header and Child class. I would like to know how to serialize child object using newtonsoft.I have tried below child object, but its return only one record where as child object contain 4 record
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; }
}
Serialize json object:-
styleBomLeatherSetupHeader.StyleStockID = styleStockSetup.StyleStockID;
styleBomLeatherSetupHeader.Details = styleBomLeatherSetups;
protected StyleBomLeatherSetupHeader styleBomLeatherSetupHeader { get; set; } = new StyleBomLeatherSetupHeader();
string json = JsonConvert.SerializeObject(styleBomLeatherSetupHeader);
CodePudding user response:
After you have the header object setup, you can point to the child list with your property "Details". And with that been said, you can serialize just that property, like this:
string detailsJson =JsonConvert.SerializeObject(styleBomLeatherSetupHeader.Details);
CodePudding user response:
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; }
}
Then
styleBomLeatherSetupHeader.StyleStockID=styleStockSetup.StyleStockID;
foreach(styleBomLeatherSetup in styleBomLeatherSetups)
{
styleBomLeatherSetupHeader.Details.Add(new StyleBomLeatherSetup{
// map your properties.
});
}
string json = JsonConvert.SerializeObject(styleBomLeatherSetupHeader);