Reputation: 4899
I'm using Google Translation API to detect a language of a string. The API is returning this JSON:
{
"data": {
"detections": [
[
{
"confidence": 0.37890625,
"isReliable": false,
"language": "ro"
}
]
]
}
}
I still haven't found the way of deserialize it. I'm using System.Runtime.Serialization
and this is my code:
[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)));
I'm getting this as a result:
Confidence: 0
IsReliable:false
Language:null
Upvotes: 1
Views: 332
Reputation: 117155
In your JSON, the value of "detections"
is a 2d jagged array:
"detections": [ [ { ... } ] ]
Therefore your model needs to reflect this by using nested collections:
[DataContract]
public class Data
{
[DataMember(Name = "detections")]
public List<List<Detection>> Detections { get; set; }
}
Upvotes: 3