要在我的Android应用程序中解决我的Windows vs linux换行符不匹配问题,我将简单地替换所有" \ r \ n"带有" \ n"的子字符串对于进入应用程序的所有数据(来自ASP.NET WebAPI REST服务),并对数据进行相反的操作。
对于入站数据来说这很容易,因为我已经有一个字符串的引用,该字符串包含序列化json数据的中间副本,我只是对此缓冲区进行了替换:
//...
string recieveBuffer;
WebRequest request = WebRequest.Create(url);
//...
WebResponse wresponse = request.GetResponse();
using (StreamReader sr = new StreamReader(wresponse.GetResponseStream()))
{
recieveBuffer = sr.ReadToEnd();
}
///////////////////////////////////////////////////////////////
recieveBuffer = recieveBuffer.Replace("\r\n","\n");
///////////////////////////////////////////////////////////////
List<T> temp = JsonConvert.DeserializeObject<List<T>>(
recieveBuffer,
new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }
);
//...
但是,在传输序列化json数据之前没有中间字符串/缓冲区,它们都发生在JsonSerializer Serialze()成员内部:
//...
string url = GetUrlRequest();
WebRequest request = WebRequest.Create(url);
//...
Stream requestStream = request.GetRequestStream();
StreamWriter streamWriter = new StreamWriter(requestStream, new UTF8Encoding(false, true));
JsonTextWriter jsonTextWriter = new JsonTextWriter(streamWriter);
serializer = JsonSerializer.Create(serializerSettings);
serializer.Serialize(jsonTextWriter, tabletData);
jsonTextWriter.Close();
streamWriter.Close();
requestStream.Close();
//...
因此,我正在寻找一种方法来保持缓冲区在传输之前保持序列化的json,以便我可以替换所有&#34; \ n&#34;带有&#34; \ r \ n&#34;。
的字符串答案 0 :(得分:0)
我重构了我的写/发送代码如下:
//...
string url = GetUrlRequest();
StringBuilder sb = new StringBuilder();
TextWriter textWriter = new StringWriter(sb);
JsonTextWriter jsonTextWriter = new JsonTextWriter(textWriter);
JsonSerializer serializer = JsonSerializer.Create(serializerSettings);
serializer.Serialize(jsonTextWriter, tabletData);
/////////////////////////////////////////////////////////////////////////
string sendBuffer = sb.ToString();
sendBuffer = sendBuffer.Replace("\n","\r\n");
/////////////////////////////////////////////////////////////////////////
WebRequest request = WebRequest.Create(url);
//...
Stream requestStream = request.GetRequestStream();
streamWriter = new StreamWriter(requestStream, new UTF8Encoding(false, true));
streamWriter.Write(sendBuffer);
jsonTextWriter.Close();
streamWriter.Close();
requestStream.Close();