首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C# 使用 Newtonsoft.Json 反序列化複雜嵌套 JSON 的完整實戰指南

     編輯:程式設計疑難解答

目標 JSON 結構

{
  "total": 1,
  "success": true,
  "metaData": { "fields": [ {"name":"presno","type":"string"}, ... ] },
  "rows": [{
    "presno": "19840491",
    "medpresinfo": "[{\"medid\":40491,...}]" // 字符串化的 JSON 數組
  }],
  "processedTime": 43
}

實體類設計

public class Response {
    public int total { get; set; }
    public bool success { get; set; }
    public MetaData metaData { get; set; }
    public List rows { get; set; }
    public int processedTime { get; set; }
}

public class MetaData {
    public List fields { get; set; }
}
public class Field { public string name; public string type; public string dateFormat; }

public class Row {
    public string presno { get; set; }
    public int medid { get; set; }
    public string medouttime { get; set; }
    // ... 其他字段
    public string medpresinfo { get; set; } // 保持字符串,二次反序列化
}

二次反序列化嵌套 JSON 字符串

var response = JsonConvert.DeserializeObject(jsonString);
foreach (var row in response.rows) {
    var medList = JsonConvert.DeserializeObject>(row.medpresinfo);
    row.MedInfos = medList; // 假設 Row 類添加此屬性
}

關鍵配置

var settings = new JsonSerializerSettings {
    NullValueHandling = NullValueHandling.Ignore,
    DateFormatString = "yyyy-MM-dd HH:mm:ss.ffffff",
    // 自定義日期格式處理 metaData.fields 中的 dateFormat
};

常見坑

  • 數字類型:JSON 中 medid 為數字,C# 用 int/long;prestype 為浮點,用 double。
  • 日期字符串:指定 DateFormatString 或使用 DateTimeOffset。
  • 嵌套字符串:medpresinfo 是字符串化的 JSON,需二次解析。

參考

Newtonsoft.Json 官方文檔:DeserializeObject

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved