Skip to main content
2 of 4
added 154 characters in body
Philipp
  • 123.2k
  • 28
  • 264
  • 345

JsonUtility.ToJson only works with objects of a class which inherits from MonoBehaviour or ScriptableObject or which has the [Serializable] attribute. So when you want to use it to create a Json message for some external API, then you should build a class which mimics the JSON object that API expects.

When that API exects just { "_email":"[email protected]" }, then you can create a class like this:

[Serializable]
private class EmailApiData {
     public string _email;
}

This class can actually be declared private within the class which uses it. So you don't necessarily need to create a new sourcecode file for it.

You can then create your JSON string like this:

string data = JsonUtility.ToJson(new EmailApiData() { _email = email.text }); 

In some cases the API might expect keys which are not valid C# identifier names. They might start with a number or are reserved C# keywords and thus can not be used as variable names. In that case you can help yourself by using the @ character in front of them:

[Serializable]
private class EmailApiData {
     public string _email;
     public string @for;
     public int @1stLoginTimestamp;
}

public void SaveData() {
    string data = JsonUtility.ToJson(new EmailApiData() { 
         _email = email.text 
         @for = someOtherString
         @1stLoginTimestamp = DateTime.Now
    }); 
    //...
}
Philipp
  • 123.2k
  • 28
  • 264
  • 345