如何使用Newtonsoft序列化生成指定结构的嵌套JSON
实现方案
1 修正实体类
你现有的实体类仅需调整Line类,补充目标JSON中小计行独有的Amountlin字段即可:
public class Line { public string Id { get; set; } public int LineNum { get; set; } public string Description { get; set; } public int Amount { get; set; } // 新增可空的Amountlin字段,仅小计行赋值 public int? Amountlin { get; set; } public string DetailType { get; set; } public SalesItemLineDetail SalesItemLineDetail { get; set; } public SubTotalLineDetail SubTotalLineDetail { get; set; } }
2 组装嵌套对象
按照从内层到外层的顺序构建对象即可,示例代码完全匹配你给出的目标JSON结构:
// 1. 构建销售行的内层对象 var salesItemLineDetail = new SalesItemLineDetail { ItemRef = new ItemRef { value = "3", name = "Test:Test Item" }, UnitPrice = 100, Qty = 1, ItemAccountRef = new ItemAccountRef { value = "6", name = "Sales" }, TaxCodeRef = new TaxCodeRef { value = "6" } }; // 2. 构建第一行(销售行) var salesLine = new Line { Id = "1", LineNum = 1, Description = "Test Sales Description", Amount = 100, DetailType = "SalesItemLineDetail", SalesItemLineDetail = salesItemLineDetail }; // 3. 构建第二行(小计行) var subTotalLine = new Line { Amountlin = 0, DetailType = "SubTotalLineDetail", SubTotalLineDetail = new SubTotalLineDetail() }; // 4. 构建TxnTaxDetail相关对象 var taxLineDetail = new TaxLineDetail { TaxRateRef = new TaxRateRef { value = "7" }, PercentBased = true, TaxPercent = 20, NetAmountTaxable = 0 }; var taxLine = new TaxLine { Amount = 0, DetailType = "TaxLineDetail", TaxLineDetail = taxLineDetail }; var txnTaxDetail = new TxnTaxDetail { TotalTax = 0, TaxLine = new List<TaxLine> { taxLine } }; // 5. 构建地址、客户相关对象 var customerRef = new CustomerRef { value = "2", name = "Test Company" }; var billAddr = new BillAddr { Id = "3", Line1 = "21 TEST TEST", Line2 = "TEST", City = "TEST", Country = "United Kingdom", PostalCode = "POSTCODE" }; var shipAddr = new ShipAddr { Id = "3", Line1 = "21 TEST TEST", Line2 = "TEST", City = "TEST", Country = "United Kingdom", PostalCode = "POSTCODE" }; // 6. 组装根对象 var root = new Root { Line = new List<Line> { salesLine, subTotalLine }, TxnTaxDetail = txnTaxDetail, CustomerRef = customerRef, BillAddr = billAddr, ShipAddr = shipAddr };
3 序列化配置
序列化时需添加忽略null值的配置,避免未赋值的属性(比如销售行的Amountlin、小计行的Id等)输出为null,匹配目标JSON格式:
using Newtonsoft.Json; var serializeSettings = new JsonSerializerSettings { // 忽略值为null的属性 NullValueHandling = NullValueHandling.Ignore, // 可选:格式化输出JSON,方便调试 Formatting = Formatting.Indented }; string jsonResult = JsonConvert.SerializeObject(root, serializeSettings);
输出的jsonResult就完全符合你给出的目标JSON格式。
内容的提问来源于stack exchange,提问作者Chris Waine
相关产品推荐
相关产品推荐

