JsonSerializationException
jayp84847 opened this issue · 5 comments
I am using json in my unity project. Everything works good in unity editor.
But when I build it for android it shows me this error.
Please guide me in it.
This is the code
DeepAI_API api = new DeepAI_API(apiKey: "quickstart-QUdJIGlzIGNvbWluZy4uLi4K");
StandardApiResponse resp = api.callStandardApi("torch-srgan", new {
image = File.OpenRead("C:\\path\\to\\your\\file.jpg"),
});
Hi @jayp84847! Thanks for reaching out!
At first glance my guess is that the error originates from the code stripping that Unity does on some platforms. My guess is that api.callStandardApi
does something like JsonConvert.DeserializeObject<StandardApiResponse>(responseBody)
, and so given that, adding something like the following should resolve your issue:
// Save this somewhere inside your Assets folder
// No need to add it to the scene, it just needs to be included
// in the compilation
using Newtonsoft.Json.Utilities;
using UnityEngine;
public class AotTypeEnforcer : MonoBehaviour
{
public void Awake()
{
AotHelper.EnsureType<DeepAI.StandardApiResponse>();
}
}
In short: Unity trims aways some methods, constructors, properties, and types that it thinks are unused, just to trim down the build size. Unity does not understand it needs to keep the constructors of the types when deserializing.
You can read more on this here:
- What is AOT and why do you need to care? https://github.com/jilleJr/Newtonsoft.Json-for-Unity/wiki/What-even-is-AOT
- Wiki on AotHelper: https://github.com/jilleJr/Newtonsoft.Json-for-Unity/wiki/Fix-AOT-using-AotHelper
- Reference docs on
AotHelper.EnsureType<T>()
: https://github.com/jilleJr/Newtonsoft.Json-for-Unity/wiki/Reference-Newtonsoft.Json.Utilities.AotHelper#aothelperensuretype
Sounds like Unity is trimming away your properties as well.
Instead of using AotHelper, you could try adding a link.xml
file instead.
Add this file somewhere inside your Assets folder. The name must be link.xml
(must be lower-cased)
<linker>
<!-- Assuming here your assembly name is DeepAI -->
<assembly fullname="DeepAI">
<type fullname="DeepAI.StandardApiResponse" />
</assembly>
</linker>
Further reading on link.xml
files: https://github.com/jilleJr/Newtonsoft.Json-for-Unity/wiki/Fix-AOT-using-link.xml
Glad to help :)