[英]DataContractJsonSerializer: serialize object or array (can be both)
I'm accessing the tomtom json api, and the api either returns me an array of objects, or a single object, when an error has happen. 我正在访问tomtom json api,并且在发生错误时,api要么返回对象数组,要么返回单个对象。
Example: 例:
[{"driverno": "...
Error Example: 错误示例:
{"errorCode": "8011","errorMsg": "request quota reached, error code: 8011"}
The data is accessed WebRequest, WebResponse and they return a stream, which can then be passed to a DataContractJsonSerializer. 通过WebRequest,WebResponse访问数据,它们返回一个流,然后可以将其传递到DataContractJsonSerializer。 However, I can't create a serialization class, which accepts both forms of JSON, and the stream can't be passed twice, because the seek function is not supported.
但是,我无法创建一个接受两种形式的JSON的序列化类,并且该流也不能传递两次,因为不支持seek函数。
Is there a way, to create a serialization class which supports both types of JSON input? 有没有办法创建一个支持两种类型的JSON输入的序列化类?
I found a workaround, where I copy the Stream
to a MemoryStream
, which enables seeking. 我找到了一种解决方法,将
Stream
复制到MemoryStream
,从而可以进行查找。 I'm not completly settisfied with th solution, becuase it does a Stream copying and the DataContractJsonSerializer
twice. 我对解决方案不完全满意,因为它两次执行流复制和
DataContractJsonSerializer
。
Sample: 样品:
string text = File.ReadAllText(PAHT);
text = Regex.Replace(text, "\\{[\\n\\r ]*\"__type", "{\"__type");
// copy to MemoryStream
using (MemoryStream dataStream = new MemoryStream(Encoding.UTF8.GetBytes(text)))
{
DataContractJsonSerializer errorDeserializer = new DataContractJsonSerializer(typeof(RequestError));
RequestError errorSerilaized = (RequestError)errorDeserializer.ReadObject(dataStream);
// check if an error happened
if (errorSerilaized.errorCode == null)
{
// seek the stream to position 0
dataStream.Position = 0;
DataContractJsonSerializer _deserializer = new DataContractJsonSerializer(typeof(NoneErrorSerializationClass));
NoneErrorSerializationClass tripReportsSerialized = (NoneErrorSerializationClass)_deserializer.ReadObject(dataStream);
// ...
}
else
{
MessageBox.Show(errorSerilaized.errorMsg);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.