Can Json.NET serialize / deserialize to / from a stream?(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: 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 一起使用,或直接使用采用 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);
这篇关于Json.NET 可以对流进行序列化/反序列化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Json.NET 可以对流进行序列化/反序列化吗?
基础教程推荐
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 如果条件可以为空 2022-01-01
- 将数据集转换为列表 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
