C#中如何生成含数组值而非序列化字符串的嵌套JSON
解决嵌套JSON中子数组被序列化为带转义字符的字符串问题
问题核心是你错误地对子数组做了两次序列化:先把paymentList序列化为字符串存入rowData,然后对整个rowData序列化时,这个字符串会被再次转义,导致payment_for变成带转义符的字符串而非数组。
修改步骤:
- 将
rowData的类型从Dictionary<string, string>改为Dictionary<string, object>,使其能够存储数组等非字符串类型的数据。 - 直接将
paymentList赋值给rowData["payment_for"],取消提前序列化的操作。
修改后的完整代码:
private List<string[]> gridDataList = new List<string[]>(); private void BindGridView() { string ss = cb_DOCUMENT_NO.SelectedValue; List<Dictionary<string, string>> MainList = new List<Dictionary<string, string>>(); // 改为Dictionary<string, object>以支持存储数组类型 Dictionary<string, object> rowData = new Dictionary<string, object>(); rowData["User_id"] = user_id; rowData["Region_Id"] = txt_REGION_ID.Text; rowData["document_no"] = ss; rowData["industry_name"] = cb_INDUSTRY_NAME.SelectedValue; rowData["customer_number"] = cb_INDUSTRY_NAME.SelectedValue; rowData["posting_date"] = txt_POSTING_DATE.Text; List<Dictionary<string, string>> paymentList = new List<Dictionary<string, string>>(); foreach (GridViewRow row in biGridView.Rows) { Dictionary<string, string> paymentData = new Dictionary<string, string>(); for (int i = 0; i < row.Cells.Count; i++) { string headerText = biGridView.HeaderRow.Cells[i].Text.Trim(); string cellText = row.Cells[i].Text.Trim(); if (cellText == " ") { cellText = string.Empty; } paymentData[headerText] = cellText.Trim(); } paymentList.Add(paymentData); } // 直接赋值数组,不再提前序列化 rowData["payment_for"] = paymentList; string jsonData = JsonConvert.SerializeObject(rowData, Formatting.Indented); Response.Write("<pre>" + jsonData + "</pre>"); PostJsonDataInLaravelApp(jsonData); }
修改后输出:
{ "User_id": "EAUSER02", "Region_Id": "ID-02", "document_no": "02-80/81-BIN-00259", "industry_name": "02-CNO-0001", "customer_number": "02-CNO-0001", "posting_date": "03-05-2080", "payment_for": [ { "BillType": "गोदाम भवन बहाल", "Description": "गोदाम भवन बहाल", "Amount": "1000.00", " ": "" } ] }
内容的提问来源于stack exchange,提问作者Salaj Subedi
相关产品推荐
相关产品推荐

