Reputation: 129
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?
Upvotes: 1
Views: 1358
Reputation: 90862
You can not create instances of MonoBehaviour
via the JsonUtility. A MonoBehaviour
only makes sense if it is attached to a GameObject
.
It is also not allowed that a MonoBehaviour
implements a constructor.
Either do not make it a MonoBehaviour
at all. And rather use
[System.Serializable]
public class PatientBackend
{
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;
}
}
and
var patientBackend = JsonUtility.FromJson<PatientBackend>(jsonString);
Or if you really need this as a MonoBehaviour
instead rather use JsonUtility.FromJsonOverwrite
in order to only overwrite the fields of an existing instance.
public class PatientBackend : MonoBehaviour
{
public int subjectid;
public string name;
public string first_name;
public string date_of_birth;
public int age;
}
and
JsonUtility.FromJsonOverwrite(jsonString, existingpatientBackend);
Upvotes: 1
Reputation: 1632
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
Upvotes: 1