Reputation: 730
I am new to Unity/C# and having difficulty converting two objects into JSON.
The goal is to build a JSON object that looks as follows:
{
"operation": "pin",
"question": {
"studentPin": "123456"
}
}
In Java I would simply do the following:
Question question = new Question();
question.setStudentPin(pin);
ServerRequest request = new ServerRequest();
request.setOperation(Constants.PIN_OPERATION);
//set the values entered for the pin entered
request.setQuestion(question);
String json = gson.toJson(request);
However, when I do the following in C#
//Creating a new Question object
Question question = new Question();
question.studentPin = pinNumber.text;
ServerRequest request = new ServerRequest();
request.operation = Constants.PIN_OPERATION;
//set the values entered for the pin entered
request.question = question;
string json = JsonConvert.SerializeObject(request);
I get the following error:
JsonSerializationException: Self referencing loop detected for property 'question' with type 'Question'.Path
I have googled this error and understand that this usually happens when in your model classes there is a reference back to a parent object and that parent object has a reference back to its child object, which causes a circular reference during serialization.
However, I am unsure how exactly I can go about resolving these issues.
My Question class is set-up as follows:
public class Question : MonoBehaviour {
public string studentPin;
}
My ServerRequest class is set-up as follows:
public class ServerRequest : MonoBehaviour {
public string operation;
public Question question;
}
Any help or guidance would be greatly appreciated.
Upvotes: 0
Views: 243
Reputation: 2303
JsonUtility.ToJson()
instead.Question
and ServerRequest
are mainly used to store data only, consider not subclassing it from MonoBehaviour
.In all:
[System.Serializable]
public class Question {
public string studentPin;
}
[System.Serializable]
public class ServerRequest {
public string operation;
public Question question;
}
//Do your instantiation, setups, etc as above.
string json = JsonUtility.ToJson(request);
Read more about Unity's serialization here.
Upvotes: 1
Reputation: 4360
You should use the JsonSerializaerSettings
class and setup reference-based serialization:
JsonSerializerSettings settings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.All,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize
};
string json = JsonConvert.SerializeObject(request, settings);
Upvotes: 0