我有以下代码来对通过流发送的JSON对象进行deserilize。
使用网络流运行此代码时,每次jsonTextReader.LinePosition
越过值1000
时,都会收到错误消息。即使它是以前成功反序列化的相同对象。即发送的所有JSON消息都已正确格式化并与Schema匹配。
当使用MemoryStream
时,奇怪的是,无论jsonTextReader.LinePosition
如何,此代码都能正常运行。
当LinePosition
超出1000
时,是否有其他人遇到过类似的问题?
var Serializer = new JsonSerializer()
{
NullValueHandling = NullValueHandling.Ignore
};
var streamReader = new StreamReader(stream, new UTF8Encoding());
var jsonTextReader = new JsonTextReader(streamReader)
{
CloseInput = false,
SupportMultipleContent = true
};
while (true)
{
if (jsonTextReader.Read())
{
message = Serializer.Deserialize<MyObject>(jsonTextReader);
}
}
PS 我无法将if (jsonTextReader.Read())
移至while
循环,因为它已在库函数中完成。简而言之,我无法改变代码流。
@ Tewr建议在源流上将maxlength
某个值限制为1000/1024。但是当我运行以下内容时,它运行正常。
while (true)
{
if (jsonTextReader.Read())
{
message = Serializer.Deserialize<MyObject>(jsonTextReader);
}
else
{
jsonTextReader = new JsonTextReader(streamReader);
}
}
但问题是,我无法做到这一点,因为如上所述,部分代码是在库中运行的。这并没有完全解决问题(如果有一个长度超过1024的JSON对象字符串怎么办?)。
现在,在创建新的JsonTextReader
时,所有内容都会重置。包括jsonTextReader.LinePosition
。所以,不要让jsonTextReader.LinePosition
点击1000
让事情发挥作用。在这种情况下,jsonTextReader.LinePosition
和NetworkStream
/ Socket
之间的关系是什么?
以下是我收到的一些错误消息:
解析数字时遇到意外的字符:T。路径&#39; timeStamp&#39;,第1行,第1026位。
的
{&#34;版本&#34;:&#34; 35&#34;&#34;时间戳&#34;:&#34; 2018-05-14T07:52:23.3347793Z&#34;,& #34;消息&#34; {&#34;类型&#34;:&#34; MSGTYPE&#34;&#34;值&#34; {&#34; ID&#34;:&#34; 44&#34;&#34; PARAMS&#34;:[&#34; AA&#34;&#34; AC&#34;&#34; BD&#34]}}}
和
无效的JavaScript属性标识符:&#34;。路径&#39; message.indicator&#39;,第1行,第1023位。
的
{&#34;版本&#34;:&#34; 35&#34;&#34;时间戳&#34;:&#34; 2018-05-14T07:52:23.3347793Z&#34;,& #34;消息&#34; {&#34;类型&#34;:&#34; MSGTYPE&#34;&#34;值&#34; {&#34; ID&#34;:&#34; 44&#34;&#34; PARAMS&#34;:[&#34; AA&#34;&#34; AC&#34;&#34; BD&#34;]}&#34;指示器&# 34;:{&#34;数据&#34;:&#34;正常&#34;&#34;指示&#34;:&#34;无&#34;}}}
使用MemoryStream
进行测试:
var str = "{\"version\":\"35\",\"timestamp\":\"2018-05-14T07:52:23.3347793Z\",\"message\":{\"type\":\"msgType\",\"value\":{\"id\":\"44\",\"params\":[\"AA\",\"AC\",\"BD\"]},\"indicator\":{\"data\":\"normal\",\"indication\":\"no\"}}}";
str += str;
str += str;
str += str;
var ms = new MemoryStream();
ms.Write(str.GetBytes(), 0, str.GetBytes().Count());
ms.Position = 0;
Console.WriteLine(string.Format("StringLength:{0}", str.Length));
var streamReader = new StreamReader(ms);
var jsonTextReader = new JsonTextReader(streamReader)
{
CloseInput = false,
SupportMultipleContent = true
};
然后像以前一样使用jsonTextReader
。