Json.NET 可以序列化/反序列化到/来自流吗?
听说 Json.NET 比 DataContractJsonSerializer 快,想试一试...
I have heard that Json.NET is faster than DataContractJsonSerializer, and wanted to give it a try...
但是我在 JsonConvert 上找不到任何采用流而不是字符串的方法.
But I couldn't find any methods on JsonConvert that take a stream rather than a string.
以在WinPhone上反序列化一个包含JSON的文件为例,我使用以下代码将文件内容读入字符串,然后反序列化为JSON.在我的(非常特别的)测试中,它似乎比使用 DataContractJsonSerializer 从流中直接反序列化慢了大约 4 倍......
For deserializing a file containing JSON on WinPhone, for example, I use the following code to read the file contents into a string, and then deserialize into JSON. It appears to be about 4 times slower in my (very ad-hoc) testing than using DataContractJsonSerializer to deserialize straight from the stream...
// DCJS
DataContractJsonSerializer dc = new DataContractJsonSerializer(typeof(Constants));
Constants constants = (Constants)dc.ReadObject(stream);
// JSON.NET
string json = new StreamReader(stream).ReadToEnd();
Constants constants = JsonConvert.DeserializeObject<Constants>(json);
我做错了吗?
UPDATE: 这不再适用于当前版本,请参阅 下面以获得正确答案(无需否决,这在旧版本上是正确的).
UPDATE: This no longer works in the current version, see below for correct answer (no need to vote down, this is correct on older versions).
使用带有 StreamReader
的 JsonTextReader
类或使用直接采用 StreamReader
的 JsonSerializer
重载:
Use the JsonTextReader
class with a StreamReader
or use the JsonSerializer
overload that takes a StreamReader
directly:
var serializer = new JsonSerializer();
serializer.Deserialize(streamReader);