我正在开发一个执行 linq to sql db 并将结果放入 VAR 变量的 WebService。然后我想使用 javascript 序列化程序(c#)将 VAR 中的结果序列化为 json 格式。像这样的东西:
var sb= from p in ent.people .........
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(sb.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, sb);
string json = System.Text.Encoding.Default.GetString(ms.ToArray());
但我收到这样的错误响应:
Type 'System.Data.Objects.ObjectQuery`1[<>f__AnonymousType2d`5[System.String,System.Nu llable`1[System.Int32],System.Nullable`1[System.Int32],System.Int32,System.String]]' cannot be serialized.
考虑使用 DataContractAttribute 属性对其进行标记,并使用 DataMemberAttribute 属性标记您想要序列化的所有成员。如果该类型是一个集合,请考虑使用 CollectionDataContractAttribute 对其进行标记。有关其他支持的类型,请参阅 Microsoft .NET Framework 文档。
如何将 LINQ 结果直接序列化为 JSON?非常感谢所有的答案!恩里科