Json parse error in WebGL

I’m trying to deserialize in a WebGL build and I keep getting this error, but it works fine in editor. I’m using JsonUtilities, but I also triet Newtonsoft.Json.

public class WebRequestTest : MonoBehaviour
{

    private PlayerData playerData;
    private MainScreen mainScreen;

    [SerializeField] private string apiUrl = "https://exemplo.com/api/seu_endpoint"; //API que deseja consumir
    [SerializeField] private string authToken = "SeuTokenAqui";
 
    private string json;


    private void Start()
    {
        mainScreen = FindObjectOfType<MainScreen>();
        playerData = FindObjectOfType<PlayerData>();
        StartCoroutine(FazerRequisicao());
    }

    public void CallRequest()
    {
        StartCoroutine(FazerRequisicao());
    }

    IEnumerator FazerRequisicao()
    {
        using (UnityWebRequest request = UnityWebRequest.Get(apiUrl))
        {
            request.downloadHandler = new DownloadHandlerBuffer();
            request.SetRequestHeader("Authorization", "Bearer " + authToken); // Adiciona o token como um cabeçalho de autorização

            yield return request.SendWebRequest();

            if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
            {
                Debug.LogError("Erro na requisição: " + request.error);
                mainScreen.RequestResponse(false);
            }
            else
            {
                mainScreen.RequestResponse(true);
                // A requisição foi bem-sucedida. Agora você pode analisar os dados JSON.
                json = request.downloadHandler.text;
                Debug.Log("Resposta da API: " + json);

                // Analisar o JSON para extrair o valor desejado (suponhamos que seja um campo "value" no JSON)
                UserData data = JsonUtility.FromJson<UserData>(json);
                // UserData data = JsonConvert.DeserializeObject<UserData>(json);
         
                if (data != null)
                {
                    float cash = data.user.cash;
                    playerData.NewUserData(cash, authToken);
                }
                else
                {
                    Debug.LogError("Erro ao analisar o JSON.");
                }
            }
        }
    }

    [System.Serializable]
    public class UserData
    {
        public User user;
    }

    [System.Serializable]
    public class User
    {
        public float cash;
    }
}
}


I thought that Firefox was causing it, but even in Microsoft Explorer I got this error

You may want to enable full stack traces in WebGL, see Unity - Manual: Debug and troubleshoot WebGL builds for more details.

With that, you might get more information about the cause of the issue.

1 Like

And verify that you get the exact same json response as in the editor.

1 Like

For some reason it’s getting a html file, but in editor is a json. Do you have any idea why this is happening?

No, that’s for you to find out. Verify that you are requesting the exact same URL and header values.

Btw, this seems odd to me:
request.downloadHandler = new DownloadHandlerBuffer();

I have not needed to assign a new handler. When the request returns, the downloadHandler is set automatically in my cases. However I worked with editor-only web requests, not runtime.

1 Like