I am trying to receive data from my backend in my unity project, the data looks like this:
{"subjectid":98,"name":"test23","first_name":"test23","date_of_birth":"1998-02-16","age":23}
I am using the following line to get the data into an object:
PatientBackend patient = JsonUtility.FromJson<PatientBackend>(responseBody);
The object looks like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class PatientBackend : MonoBehaviour
{
public int subjectid;
public string name;
public string first_name;
public string date_of_birth;
public int age;
public PatientBackend(string name, string first_name, string date_of_birth)
{
this.name = name;
this.first_name = first_name;
this.date_of_birth = date_of_birth;
}
}
But everytime this is called it thows the following exception:
System.ArgumentException: Cannot deserialize JSON to new instances of type 'PatientBackend.'
at UnityEngine.JsonUtility.FromJson (System.String json, System.Type type) [0x00056] in <5070e0347dee4c9faba7201166fbed9d>:0
at UnityEngine.JsonUtility.FromJson[T] (System.String json) [0x00001] in <5070e0347dee4c9faba7201166fbed9d>:0
at DataService+<createPatient>d__8.MoveNext () [0x0021b] in C:\Users\diete\Documents\Stage\bedrijf_CLEAN-CLONE\VRStrokeRehabilitation\Unity\UnityProject\Assets\Scripts\DataService.cs:87
UnityEngine.Debug:Log(Object)
<createPatient>d__8:MoveNext() (at Assets/Scripts/DataService.cs:90)
Does anyone know why this isn't working?
PatientBackend
should not be a MonoBehaviour. The JsonUtility can only be used for data classes. MonoBehaviours are components which need to be attached to gameobjects. You can't simply "create" an instance, that's why it failed.
see Answers.unity