使用SSIS调用API遇System.MissingMethodException错误求解(无C#基础)
解决SSIS调用API反序列化时的MissingMethodException错误
问题根源
- JSON结构不匹配:目标API返回的JSON顶层是一个包含
data字段的对象,而非直接的人口数据数组。直接将整个JSON反序列化成DrillDowns[],会导致序列化器无法正确解析结构,触发构造函数相关错误。 - 无效的字符串修改:代码中
jsonString = reader.ReadToEnd().Replace("\\", "")属于多余操作,API返回的JSON没有多余的转义反斜杠,这一步会破坏原始JSON的完整性。 - 构造函数显式声明缺失:虽然C#自动属性会隐式生成无参构造函数,但在SSIS脚本组件环境中,显式声明无参构造函数可以避免序列化器的潜在识别问题。
修改后的完整代码
public override void CreateNewOutputRows() { string wUrl = "https://datausa.io/api/data?drilldowns=Nation&measures=Population"; try { DrillDowns[] populationOutput = GetWebServiceResult(wUrl); foreach (var value in populationOutput) { Output0Buffer.AddRow(); Output0Buffer.Population = value.Population; Output0Buffer.Year= value.Year; Output0Buffer.Nation = value.Nation; } } catch (Exception ex) { FailComponent(ex.ToString()); } } private DrillDowns[] GetWebServiceResult(string wUrl) { HttpWebRequest httpWReq= (HttpWebRequest)WebRequest.Create(wUrl); HttpWebResponse httpWResp = (HttpWebResponse)httpWReq.GetResponse(); DrillDowns[] jsonResponse = null; try { if (httpWResp.StatusCode == HttpStatusCode.OK) { Stream responseStream= httpWResp.GetResponseStream(); string jsonString = null; using (StreamReader reader = new StreamReader(responseStream)) { // 去掉多余的Replace操作 jsonString = reader.ReadToEnd(); } JavaScriptSerializer sr = new JavaScriptSerializer(); // 先反序列化为根对象,再提取data数组 ApiResponse apiResponse = sr.Deserialize<ApiResponse>(jsonString); jsonResponse = apiResponse.data; } else { FailComponent(httpWResp.StatusCode.ToString()); } } catch (Exception ex) { FailComponent(ex.ToString()); } return jsonResponse; } private void FailComponent(string errorMsg) { bool fail = false; IDTSComponentMetaData100 compMetadata = this.ComponentMetaData; compMetadata.FireError(1, "Error getting data from Webservice!!", errorMsg, "", 0, out fail); } // 新增根对象类,匹配API返回的JSON结构 public class ApiResponse { public DrillDowns[] data { get; set; } } // 显式添加无参构造函数的实体类 public class DrillDowns { public DrillDowns() {} public string Nation { get; set; } public string Year { get; set; } public int Population { get; set; } }
额外说明
- 可直接访问API链接查看返回的JSON结构,或用在线JSON格式化工具解析,确保实体类结构和JSON完全匹配。
- 在SSIS脚本组件中,需确保已引用
System.Web.Extensions程序集(JavaScriptSerializer依赖该引用)。
内容的提问来源于stack exchange,提问作者Dshoww
相关产品推荐
相关产品推荐

