- Home /
Having issues when multithreading and deserializing JSON with JSONUtility
Hello everybody!
I am having a problem. There is a part of my code where i need do deserialize a very big JSON. Since it is a lot of effort to do that and I don't want to stop the UI and other important stuff i decided to execute the serialization in a separate thread. And then callback to the main thread when the deserialization is complete.
But differently than what i expected, the UI and the rest of execution stops and wait for the deserialization to complete as if there were no separate thread. Obs: The deserialization works fine. The problem is that the execution stops as if there were no threads.
My code is somewhat as follows:
IEnumerator DeserializeObjectAsync(string json,Action<MyObject> callback){
bool threadFinished = false;
MyObject deserializedObject = null;
Thread t = new Thread (delegate() {
deserializedObject = JsonUtility.FromJson<MyObject>(json);
threadFinished = true;
});
t.Start ();
while(!threadFinished){
yield return new WaitForEndOfFrame ();
}
callback(deserializedObject);
}
Does someone know what may be the issue or how to solve it? Thank you!
Did you find any solution to this?, I am also running into the same issue.
Is the JsonUtility even thread safe? It was my understanding that you should avoid using most of the unity api on other threads as anything outside of the struct types are not thread safe. $$anonymous$$ay be completely unrelated to your issue, just curious is you can confirm that JsonUtility is threadsafe or not.
Yes it is https://docs.unity3d.com/ScriptReference/JsonUtility.FromJson.html
The versions of this method that take strings can be called from background threads
I don't use JsonUtility as it has limitations. I use JSONDeserializer,
Did it solve the problem, changing to JSONDeserializer?
I did not find any solution at all, until now, no :-( $$anonymous$$aybe, changing the deserialization method could work... But I am not sure.
Answer by hippogames · Dec 05, 2021 at 11:02 AM
Hi, just use Newtonsoft JSON, it works fine.
private IEnumerator DeserializeInThread(string json)
{
List<UserImage> images = null;
var thread = new Thread(() => images = JsonConvert.DeserializeObject<List<UserImage>>(json));
thread.Start();
while (images == null)
{
yield return null;
}
}
Your answer
Follow this Question
Related Questions
ArgumentException: Cannot deserialize JSON to new instances of type 0 Answers
Parse JSON Data with JSON Utility to Dictionary object 1 Answer
Deserialize Json into list.,how to deserialize a list via .FromJson 1 Answer
Instantiating many objects during update lags 1 Answer
Application.ExternalCall Issue 0 Answers