Assistance with JSON response

Hi

Having some issues with JSON using Google Translate API. Not sure where my error is. Would anyone be able to advise?

Here is the response text

{
“data”: {
“translations”: [
{
“translatedText”: “vamos a la tienda”,
“model”: “nmt”
}
]
}
}

Receiving a null reference at line 7

Debug.Log("Received: " + www.downloadHandler.text);
                //TranslationResponse translationResponse = JsonConvert.DeserializeObject<TranslationResponse>(www.downloadHandler.text);
                translationResponse = JsonConvert.DeserializeObject<TranslationResponse>(www.downloadHandler.text);
                Debug.Log(translationResponse);
                Debug.Log(translationResponse.TranslationData); // Error here TranslationData is null
                OnTranslated(translationResponse.TranslationData.Translations[0].TranslatedText);

public class TranslationResponse
{
    public TranslationData TranslationData;
}

public class TranslationData
{
    public List<Translation> Translations;
}

public class Translation
{
    public string TranslatedText;
    public string Model;
}

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null
  • Identify why it is null
  • Fix that

Networking, UnityWebRequest, WWW, Postman, curl, WebAPI, etc:

And setting up a proxy can be very helpful too, in order to compare traffic:

Well I see two issues here:

  • None of your classes have the Serializable attribute.
  • The fields in your class do not match the key names in your json. So it can not possibly match them.
"TranslationData" is not "data"
"Translations" is not "translations"
"TranslatedText" is not "translatedText"
"Model" is not "model"
3 Likes

Thank you Bunny83