Silverlight json won't serialize

2019-08-27 17:55发布

问题:

I have been trying to serialize some json data in Silverlight. I am using the following code

System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(stacks.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, stacks);
StreamReader reader = new StreamReader(ms);
string json = reader.ReadToEnd();

to attempt the serialization. It does not work. It was the only example I could find that did not produce errors in Visual Studio. I am passing a list of custom coded objects (stacks). When I try to view the results I am getting a blank string. Anyone got some ideas on how to point me in the right direction?

回答1:

The stream cursor is pointing to the end (after everything was written). Add the line "ms.Position = 0;" before creating the StreamReader.