gpt4 book ai didi

c# - 使用 C# 从 Google Translation API 反序列化 JSON

转载 作者:太空宇宙 更新时间:2023-11-03 22:56:54 25 4
gpt4 key购买 nike

我正在使用 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" 的值是一个二维锯齿状数组:

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

因此您的模型需要使用嵌套集合来反射(reflect)这一点:

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

关于c# - 使用 C# 从 Google Translation API 反序列化 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44978434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com