views:

1122

answers:

2

I've got the JSON coming back like this:

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

And I need to parse it into a ResponseData object I have set-up:

    public class ResponseData
    {
        public string translatedText = string.Empty;

        public object responseDetails = null;

        public HttpStatusCode responseStatus = HttpStatusCode.OK;
        public List<ResponseData> responseData { get; set; }
    }

I Deserialize it like this:

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

But no matter what the translated text is always empty.

+2  A: 

you should think about the JSON object graph represented in that string.

You can nest types for deserializating objects with different properties/fields using generics like so:

 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);

}

CVertex