![](/img/trans.png)
[英]XML deserialization: Data at the root level is invalid. Line 1 position 1. Tried almost everything
[英]API Microsoft Translator Exception: “The data at the root level is invalid. Line 1, position 1.”
我正在将微软翻译从 v2 迁移到 v3。 但我收到以下异常:
反序列化 System.String 类型的 object 时出错。 根级别的数据无效。 第 1 行,position 1。
(System.Runtime.Serialization.SerializationException)内部异常:根级别的数据无效。 第 1 行,position 1。
System.Exception {System.Xml.XmlException}
此错误发生在这行代码上:
translation.Append((string)dcs.ReadObject(response));
完整方法:
public string TranslateText(string from, string to, string text)
{
var token = string.Empty;
try
{
retryPolicy.Execute(() =>
{
token = azureAuthentication.GetAccessToken();
});
var translation = new StringBuilder();
int charLength = Configuration.Configuration.CharLength;
List<string> lines = text.Split('.').Aggregate(new[] { "" }.ToList(), (a, x) =>
{
var last = a[a.Count - 1];
if ((last + x).Length > charLength)
{
a.Add(x);
}
else
{
a[a.Count - 1] = ($"{last}{x}.");
}
return a;
});
foreach (var str in lines)
{
string uri =$"https://api.cognitive.microsofttranslator.com/languages?api-version=3.0&scope=translation&textType={HttpUtility.UrlEncode(str)}&from=from_lang&to=to_lang";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Headers.Add("Authorization", token);
try
{
retryPolicy.Execute(() =>
{
using (var response = httpWebRequest.GetResponse().GetResponseStream())
{
var dcs = new DataContractSerializer(Type.GetType("System.String"));
translation.Append((string)dcs.ReadObject(response));
}
});
}
catch (Exception ex)
{
throw new ExternalServiceUnavailableException(ex.Message, ex);
}
}
return translation.ToString();
}
catch(Exception ex)
{
throw new ExternalServiceUnavailableException(ex.Message, ex);
}
}
我不知道为什么会发生此错误。 我查看了有关此错误的其他问题,但我不确定如何在此处实施这些解决方案。
谢谢
我认为您的请求出现错误,因此反序列化失败。 我认为这部分from=from_lang&to=to_lang
应该是from={from_lang}&to={to_lang}
您正在设置文字字符串 from_lang,而不是有效语言的名称,如 en 或 es。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.