从C#中的api访问JSON对象



我正在做一个微软认知服务项目,该项目涉及语言检测和文本翻译。

我正在接收来自Microsoft Api的Json,我想将其作为对象访问。我尝试了一些不同的东西,包括JsonConvert.DeserializeObject,并将其映射到我自己的对象。(以下示例(

// Send the request and get response.
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
// Read response as a string.
if (response.ReasonPhrase == "OK")
{
//string result = await response.Content.ReadAsStringAsync();
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(result); 
}

//回应:

[{
"detectedLanguage":
{
"language":"fi",
"score":1.0
},
"translations": 
[
{"text":"This is a test, I hope it works. The text is in Finnish.","to":"en"},
{"text":"Dette er en test, jeg håber det virker. Teksten er på finsk.","to":"da"}
]
}]

//我找到了一个在线工具来生成映射的适当类

public class DetectedLanguage
{
[JsonPropertyName("language")]
public string Language { get; set; }
[JsonPropertyName("score")]
public double Score { get; set; }
}
public class Translation
{
[JsonPropertyName("text")]
public string Text { get; set; }
[JsonPropertyName("to")]
public string To { get; set; }
}
public class MyArray
{
[JsonPropertyName("detectedLanguage")]
public DetectedLanguage DetectedLanguage { get; set; }
[JsonPropertyName("translations")]
public List<Translation> Translations { get; set; }
}
public class Root
{
[JsonPropertyName("MyArray")]
public List<MyArray> MyArray { get; set; }
}

//获取时的错误

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'textananlytics_test.Root' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.'

您可以更改

Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(result); 

List<MyArray> list = JsonConvert.DeserializeObject<List<MyArray>>(result); 
Root myDeserializedClass=new Root{MyArray=list};

在您的情况下,JSON必须具有下一个结构:

{
"MyArray": [
{ /* MyArray jobject */ },
{ /* MyArray jobject */ },
...
]
}

所以依依你写了正确的处理

相关内容

  • 没有找到相关文章

最新更新