I reviewed your code and identified the issue causing the error. The problem stems from the use of an anonymous object when serializing the JSON request. Unity’s JsonUtility.ToJson() does not support anonymous types, which can lead to improper serialization and an invalid request format.
Issue:
Your code currently defines the request payload as:
var requestData = new
{
charID = characterId,
backstory = Backstory
};
However, JsonUtility.ToJson() requires an explicitly declared class marked as [System.Serializable].
To resolve this, I have modified your script to use a properly structured CharacterData class.
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using System.Text;
using TMPro;
using UnityEngine.UI;
public class ConvaiNPCBackground : MonoBehaviour
{
private string apiKey = "XXXXX"; // Hidden API key
private string updateCharacterUrl = "https://api.convai.com/character/update";
public TMP_InputField inputField;
public Button submitButton;
[System.Serializable]
public class CharacterData
{
public string charID;
public string backstory;
}
private void Start()
{
submitButton.onClick.AddListener(UpdateCharacter);
}
public void UpdateCharacter()
{
string characterId = "975cc5ee-eb2f-11ef-bac5-42010a7be016";
string backstory = inputField.text;
StartCoroutine(UpdateCharacterCoroutine(characterId, backstory));
}
private IEnumerator UpdateCharacterCoroutine(string characterId, string backstory)
{
// Create a properly structured request object
CharacterData requestData = new CharacterData
{
charID = characterId,
backstory = backstory
};
string json = JsonUtility.ToJson(requestData);
byte[] jsonData = Encoding.UTF8.GetBytes(json);
Debug.Log("Sending JSON: " + json); // Debug JSON to verify before sending
using (UnityWebRequest request = new UnityWebRequest(updateCharacterUrl, "POST"))
{
request.uploadHandler = new UploadHandlerRaw(jsonData);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
request.SetRequestHeader("CONVAI-API-KEY", apiKey);
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
Debug.Log("Character backstory updated successfully: " + request.downloadHandler.text);
}
else
{
Debug.LogError("Error updating character backstory: " + request.error);
Debug.LogError("Response: " + request.downloadHandler.text);
}
}
}
}