在SSIS脚本组件C#中反序列化MongoDB的$date字段(无Newtonsoft)
解决SSIS脚本组件中反序列化MongoDB $date格式日期的问题
问题根源
- 你的
Jsondatetime类属性名与JSON中的$date键不匹配,导致JavaScriptSerializer无法正确映射字段,进而出现空引用异常或空白输出。 - 未将字符串格式的日期转换为
DateTime类型,无法直接赋值给输出缓冲区的日期字段。
修正后的代码实现
1. 调整实体类(匹配JSON字段)
需要使用ScriptName属性指定JSON中的键名,确保序列化器能正确映射$date字段:
using System.Web.Script.Serialization; public class Student { public string studentId { get; set; } public JsonDateTime LastUpdatedDateTime { get; set; } } public class JsonDateTime { [ScriptName("$date")] // 指定JSON中的键名为$date public string DateString { get; set; } }
2. 修正反序列化与日期转换逻辑
public override void CreateNewOutputRows() { string jsonFileContent = File.ReadAllText(@"C:\desktop\sample.json"); JavaScriptSerializer js = new JavaScriptSerializer(); List<Student> allStudents = js.Deserialize<List<Student>>(jsonFileContent); foreach (var student in allStudents) { Output0Buffer.AddRow(); Output0Buffer.StudentId = student.studentId; // 处理日期字段,避免空引用异常 if (student.LastUpdatedDateTime != null && !string.IsNullOrEmpty(student.LastUpdatedDateTime.DateString)) { // 将ISO8601格式字符串转换为DateTime if (DateTime.TryParse(student.LastUpdatedDateTime.DateString, out DateTime lastUpdated)) { Output0Buffer.LastUpdatedDateTime = lastUpdated; System.Windows.Forms.MessageBox.Show($"Student {student.studentId} 最后更新时间: {lastUpdated.ToString()}"); } else { // 解析失败时标记字段为Null Output0Buffer.LastUpdatedDateTime_IsNull = true; } } else { Output0Buffer.LastUpdatedDateTime_IsNull = true; } } }
注意事项
- 确保在SSIS脚本组件中引用
System.Web.Extensions程序集(JavaScriptSerializer位于该程序集内)。 - 你的示例JSON中
studentId值缺少双引号,实际文件需修正为"studentId":"A2336"格式,否则反序列化会失败。 - 若需更严格的日期解析,可使用
ParseExact指定格式:DateTime lastUpdated = DateTime.ParseExact( student.LastUpdatedDateTime.DateString, "yyyy-MM-dd'T'HH:mm:ss.fff'Z'", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal );
内容的提问来源于stack exchange,提问作者Lazytitan
相关产品推荐
相关产品推荐

