[英]Deserialize JSON to c# object raising an exception
您能否幫助我將以下JSON反序列化為c#。
[
{
"detectedLanguage": {
"language": "en",
"score": 10.0
},
"translations": [
{
"text": "",
"to": "da"
},
{
"text": "",
"to": "da"
}
]
}
]
我已經使用以下c#類進行反序列化,但是卻遇到了異常。
public class DetectedLanguage
{
public string language { get; set; }
public int score { get; set; }
}
public class Translation
{
public string text { get; set; }
public string to { get; set; }
}
public class RootObject
{
public DetectedLanguage detectedLanguage { get; set; }
public List<Translation> translations { get; set; }
}
我的反序列化代碼是:
var response = client.SendAsync(request).Result;
var jsonResponse = response.Content.ReadAsStringAsync().Result;
var result = JsonConvert.DeserializeObject<RootObject>(jsonResponse);
例外
無法將當前JSON數組(例如[1,2,3])反序列化為類型'RootObject',因為該類型需要JSON對象(例如{“ name”:“ value”})才能正確反序列化。 要解決此錯誤,可以將JSON更改為JSON對象(例如{“ name”:“ value”}),也可以將反序列化類型更改為數組,或者將實現集合接口的類型(例如ICollection,IList)更改為List,例如List從JSON數組反序列化。 還可以將JsonArrayAttribute添加到類型中,以強制其從JSON數組反序列化。 路徑'',第1行,位置1。
score屬性有時保持浮點值,但是在我的c#類中,存在導致異常的數據類型int 。 在@Ivan Salo發表評論之前,我沒有注意到。 更改數據類型int以浮動解決了我的問題。我還使用List反序列化了@Jon Skeet在注釋部分中建議的JSON。
public class DetectedLanguage
{
public string language { get; set; }
public float score { get; set; }
}
編輯為完整答案:
using Newtonsoft.Json;
class Program
{
public partial class RootObject
{
[JsonProperty("detectedLanguage")]
public DetectedLanguage DetectedLanguage { get; set; }
[JsonProperty("translations")]
public Translation[] Translations { get; set; }
}
public partial class DetectedLanguage
{
[JsonProperty("language")]
public string Language { get; set; }
[JsonProperty("score")]
public long Score { get; set; }
}
public partial class Translation
{
[JsonProperty("text")]
public string Text { get; set; }
[JsonProperty("to")]
public string To { get; set; }
}
public partial class RootObject
{
public static RootObject[] FromJson(string jsonresponse) => JsonConvert.DeserializeObject<RootObject[]>(jsonresponse);
}
static void Main(string[] args)
{
var response = client.SendAsync(request).Result;
var jsonResponse = response.Content.ReadAsStringAsync().Result;
var result = RootObject.FromJson(jsonResponse);
System.Console.WriteLine(result[0].DetectedLanguage.Language); //outputs "en"
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.