gpt4 book ai didi

c# - 反序列化 jSON Google AJAX 翻译 API

转载 作者:行者123 更新时间:2023-11-30 22:51:06 24 4
gpt4 key购买 nike

我得到了这样返回的 JSON:

{
"responseData": [{
"responseData": {
"translatedText": "elefante"
},
"responseDetails": null,
"responseStatus": 200
}, {
"responseData": {
"translatedText": "Burro"
},
"responseDetails": null,
"responseStatus": 200
}],
"responseDetails": null,
"responseStatus": 200
}

我需要将它解析为我设置的 ResponseData 对象:

public class ResponseData 
{
public string translatedText = string.Empty;
public object responseDetails = null;
public HttpStatusCode responseStatus = HttpStatusCode.OK;
public List <ResponseData> responseData { get;set; }
}

我这样反序列化它:

JavaScriptSerializer serializer = new JavaScriptSerializer();
ResponseData translation =
serializer.Deserialize<ResponseData>(responseJson);

但无论翻译成什么,文本总是空的。

最佳答案

您应该考虑该字符串中表示的 JSON 对象图。

您可以使用泛型嵌套类型来反序列化具有不同属性/字段的对象:

class Response < T > {
public ResponseData < T > [] responseData = new ResponseData < T > [0];
public HttpStatusCode responseStatus;
public object responseDetails;
}

public class ResponseData < TInternal > {
public TInternal responseData;
public HttpStatusCode responseStatus;
public object responseDetails;
}

public class TranslatedText {
public string translatedText;
}

[Test]
public void Sample() {
var input = @ " {
""
responseData "": [{
""
responseData "": {
""
translatedText "": ""
elefante ""
},
""
responseDetails "": null,
""
responseStatus "": 200
}, {
""
responseData "": {
""
translatedText "": ""
Burro ""
},
""
responseDetails "": null,
""
responseStatus "": 200
}],
""
responseDetails "": null, ""
responseStatus "": 200
}
";

var json = new JavaScriptSerializer();
var response = json.Deserialize < Response < TranslatedText >> (input);
Assert.AreEqual(response.responseData[0].responseData.translatedText, "elefante");
Assert.AreEqual(response.responseStatus, HttpStatusCode.OK);
}

关于c# - 反序列化 jSON Google AJAX 翻译 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/172102/

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