可以Json.NET序列化/反序列化从流/? [英] Can Json.NET serialize / deserialize to / from a stream?
问题描述
我听说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.
有关反序列化包含JSON上WinPhone一个文件,例如,我用下面的code读取文件内容转换为字符串,然后反序列化到JSON。这似乎是约4倍慢于我的(非常特别)测试比使用DataContractJsonSerializer从流直反序列...
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);
难道我做错了?
Am I doing it wrong?
谢谢
暗利。
推荐答案
更新::此不再在当前版本的作品,看的下面为正确答案(没必要否决,这是正确的旧版本)。
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).
使用了 JsonTextReader
类与的StreamReader
或 JsonSerializer
重载需要一个的StreamReader
直接:
Use the JsonTextReader
class with a StreamReader
or use the JsonSerializer
overload that takes a StreamReader
directly:
var serializer = new JsonSerializer();
serializer.Deserialize(streamReader);
这篇关于可以Json.NET序列化/反序列化从流/?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!