簡體   English   中英

使用C#從Google Translation API反序列化JSON

[英]Deserialize a JSON from Google Translation API using C#

我正在使用Google Translation API來檢測字符串的語言。 API返回此JSON:

{
    "data": {
        "detections": [
            [
                {
                    "confidence": 0.37890625,
                    "isReliable": false,
                    "language": "ro"
                }
            ]
        ]
    }
}

我還沒有找到反序列化的方法。 我正在使用System.Runtime.Serialization ,這是我的代碼:

[DataContract]
public class GoogleTranslationResponse
{
    [DataMember(Name = "data")]
    public Data Data { get; set; }
}
[DataContract]
public class Data
{
    [DataMember(Name = "detections")]
    public List<Detection> Detections { get; set; }
}

[DataContract]
public class Detection
{
    [DataMember(Name = "confidence")]
    public decimal Confidence { get; set; }

    [DataMember(Name = "isReliable")]
    public bool IsReliable { get; set; }

    [DataMember(Name = "language")]
    public string Language { get; set; }
}
// ...
var jsonSerializer = new DataContractJsonSerializer(typeof(GoogleTranslationResponse));
result = (GoogleTranslationResponse)jsonSerializer.ReadObject( new MemoryStream(Encoding.Unicode.GetBytes(responseData)));

我得到了這個結果:

Confidence: 0
IsReliable:false
Language:null

在您的JSON中, "detections"的值是一個2d鋸齒狀數組:

"detections": [ [  { ... } ] ]

因此,您的模型需要通過使用嵌套集合來反映這一點:

[DataContract]
public class Data
{
    [DataMember(Name = "detections")]
    public List<List<Detection>> Detections { get; set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM