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 classes with the [Serializable] attribute which mimic the JSON objects that API expects.
When that API exects a format like this:
{"profiles": [
{"email":"[email protected]"},
{"email":"[email protected]"} ]
}`
then you can create two classes like this:
[Serializable]
private class ApiDataProfile {
public string email;
}
[Serializable]
private class ApiData {
public ApiDataProfile[] profiles;
}
These classes can actually be declared private within the class which uses itthem. So you don't necessarily need to create a new sourcecode filefiles for itthem.
You can then create your JSON string by using object and collection initializers:
string data = JsonUtility.ToJson(
new ApiData() {
profiles = new ApiDataProfile[] {
new ApiDataProfile() { email = "[email protected]" },
new ApiDataProfile() { email = "[email protected]" }
}
}
);
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
});
//...
}