我的任务包括创建一个Blazor应用程序,在那里我将使用Azure Translator,但我一直收到这个错误:
"严重性代码描述项目文件行禁止显示状态错误CS1061"object"不包含的定义"SerializeObject"且没有可访问的扩展方法"SerializeObject"可以找到接受"object"类型的第一个参数(你是缺少using指令或程序集引用?(">
这是代码,我一直在28、40和57行得到错误。
namespace BlazorTranslator.Data
{
public class TranslationService
{
public object JsonConvert { get; private set; }
public async Task<TranslationResult[]> GetTranslatation(string textToTranslate, string targetLanguage)
{
string subscriptionKey = "17e194b6968245339780ce0c266ea2bf";
string apiEndpoint = "https://api.cognitive.microsofttranslator.com/";
string route = $"/translate?api-version=3.0&to={targetLanguage}";
string requestUri = apiEndpoint + route;
TranslationResult[] translationResult = await TranslateText(subscriptionKey, requestUri, textToTranslate);
return translationResult;
}
async Task<TranslationResult[]> TranslateText(string subscriptionKey, string requestUri, string inputText)
{
object[] body = new object[] { new { Text = inputText } };
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(requestUri);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
string result = await response.Content.ReadAsStringAsync();
TranslationResult[] deserializedOutput = JsonConvert.DeserializeObject<TranslationResult[]>(result);
return deserializedOutput;
}
}
public async Task<AvailableLanguage> GetAvailableLanguages()
{
string endpoint = "https://api.cognitive.microsofttranslator.com/languages?api-version=3.0&scope=translation";
var client = new HttpClient();
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Get;
request.RequestUri = new Uri(endpoint);
var response = await client.SendAsync(request).ConfigureAwait(false);
string result = await response.Content.ReadAsStringAsync();
AvailableLanguage deserializedOutput = JsonConvert.DeserializeObject<AvailableLanguage>(result);
return deserializedOutput;
}
}
}
}
问题出现在这一行public object JsonConvert { get; private set; }
中,正如您在类中定义的那样,但您希望使用NewtonSoft库。所以你必须为这个库安装金块包并使用它。
删除行CCD_ 2并将名称空间CCD_。
https://www.newtonsoft.com/json