Serialize Linq Results Directly in JSON

I am developing a WebService that excecute linq for sql db and puts the results in a VAR variable. Then I want to serialize the result in VAR format to json using javascript serializer (C #). Something like that:

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()); 

BUT I GOT A RESPONSIBILITY ERROR AS IT:

 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. 

Consider labeling it with the DataContractAttribute attribute and mark all of its members that you want to serialize with the DataMemberAttribute attribute. If the type is a collection, consider labeling it with CollectionDataContractAttribute. See the Microsoft.NET Framework documentation for other supported types.

HOW CAN I SEARCH LINQ RESULTS DIRECTLY FOR JSON? Thanks so much for the answers! Enrico

+4
source share
2 answers

DataContractJsonSerializer does not support anonymous objects. If you want to serialize anonymous objects, you can use the JavaScriptSerializer class:

 var sb = from p in ent.people ......... var serializer = new JavaScriptSerializer(); string json = serializer.Serialize(sb); 
+4
source

At my last job, we saw this behavior, and it took a bit to do to get around it.

First, you want the IQ Toolkit, available from CodePlex, to be free. His libraries have a “PartialEvaluator” that can reduce the complexity of many expression trees by looking for nodes that always evaluate simpler nodes and replacing references to “external closures” with constants. You will want to run your IQueryable before trying to serialize it.

Then, to use the JSON serializer of the DataContract, you must configure the class that you want to serialize as a DataContract. There are teaching aids for this all over the world; basically you just decorate the class, any contained classes and members that you want to serialize with attributes.

Once you have these two things, your object and its IQueryable member should be serialized to JSON using the DataContractJsonSerializer.

0
source

All Articles