反序列化 JSON Google AJAX 翻译 API

Posted

技术标签:

【中文标题】反序列化 JSON Google AJAX 翻译 API【英文标题】:Deserialize jSON Google AJAX Translation API 【发布时间】:2010-09-15 09:15:28 【问题描述】:

我得到的 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);

但是不管翻译什么文字总是空的。

【问题讨论】:

您是在使用来自 ASP.NET AJAX 的 System.Web.Script.Serialization.JavaScriptSerializer 类,还是第三方序列化器? 【参考方案1】:

您应该考虑该字符串中表示的 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);

【讨论】:

以上是关于反序列化 JSON Google AJAX 翻译 API的主要内容,如果未能解决你的问题,请参考以下文章

spring mvc接收ajax提交的JSON数据,并反序列化为对象

如何使用 Google 的 Gson API 正确反序列化 JSON?

EXTJS-简单的ajax请求,带有回调和json到对象的反序列化

WCF 无法反序列化 JSON 请求

解决.NETMVC(ajax)Json请求太大,无法反序列化(The JSON request was too large to be deserialized)问题

如何在 asp.net 中反序列化 Json-Object