我有这样的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);
但无论翻译的文本总是空的。
答案 0 :(得分:3)
您应该考虑该字符串中表示的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);
}